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

Python中使用rfc822模块发送邮件

发布时间:2023-12-16 13:20:15

在Python中,可以使用rfc822模块来发送包含附件的邮件。以下是一个使用rfc822模块的例子:

import rfc822
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

# 邮件发送者和接收者的地址
sender = 'sender@example.com'
receivers = ['receiver1@example.com', 'receiver2@example.com']

# 创建MIMEMultipart对象,作为邮件的根容器
msg = MIMEMultipart()
msg['Subject'] = 'Test Email with Attachment'
msg['From'] = sender
msg['To'] = ",".join(receivers)

# 添加邮件正文
body = MIMEText('This is the body of the email')
msg.attach(body)

# 添加附件
attachment = MIMEText(open('example.txt', 'rb').read(), 'plain')
attachment.add_header('Content-Disposition', 'attachment', filename='example.txt')
msg.attach(attachment)

# 连接到邮件服务器并发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'username'
smtp_password = 'password'

try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.ehlo()
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.sendmail(sender, receivers, msg.as_string())
    server.close()
    print('Email sent successfully')
except Exception as e:
    print('Email could not be sent:', str(e))

在上面的例子中,我们首先导入了rfc822模块以及其他相关的模块。然后,我们定义了邮件发送者和接收者的地址。

接下来,我们创建了一个MIMEMultipart对象作为邮件的根容器,并设置了邮件的主题、发件人和收件人。然后,我们添加了邮件正文和附件。

在添加附件时,我们使用了MIMEText对象来读取文件内容并指定附件的类型。然后,我们使用add_header方法来设置附件的头信息。

最后,我们通过连接到邮件服务器并发送邮件来完成邮件的发送。在这个例子中,我们使用了SMTP协议来发送邮件,并使用了starttls方法来启用TLS加密。