欢迎访问宙启技术站
智能推送

Python发送带有回复人的MIMEText邮件

发布时间:2023-12-11 13:49:16

下面是一个通过Python发送带有回复人的MIMEText邮件的示例代码:

import smtplib
from email.mime.text import MIMEText

def send_email(sender, sender_password, recipient, subject, message, reply_to):
    # 创建一个MIMEText对象
    msg = MIMEText(message)

    # 设置发件人、收件人、主题和回复人
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = subject
    msg['Reply-To'] = reply_to

    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender, sender_password)

        # 发送邮件
        server.sendmail(sender, recipient, msg.as_string())
        print("邮件发送成功!")
    except Exception as e:
        print("邮件发送失败:" + str(e))
    finally:
        # 关闭连接
        server.quit()

# 设置发件人、收件人、主题、邮件内容和回复人
sender = 'your_email@gmail.com'
sender_password = 'your_password'
recipient = 'recipient_email@example.com'
subject = '测试邮件'
message = '这是一封测试邮件。'
reply_to = 'reply_to_email@example.com'

# 发送邮件
send_email(sender, sender_password, recipient, subject, message, reply_to)

在代码中,我们使用了email.mime.text模块来创建一个MIMEText对象。然后,我们设置了发件人、收件人、主题和回复人的相关字段。然后,我们连接到SMTP服务器,并通过SMTP服务器发送邮件。

请注意,你需要将your_email@gmail.comyour_password替换为你自己的发件人邮箱和密码,recipient_email@example.com为收件人邮箱,reply_to_email@example.com为回复人邮箱。另外,你还需要确保你的发件人邮箱允许使用SMTP服务器发送邮件。

运行上述代码后,你将会在控制台上看到邮件发送的结果信息。

这是发送带有回复人的MIMEText邮件的一个简单例子。你可以根据你的需求进行更多的定制,如添加附件、HTML内容等。希望对你有所帮助!