如何在Python中使用email.encoders模块发送带有附件的邮件
发布时间:2024-01-12 01:59:09
要在Python中发送带有附件的邮件,可以使用email和smtplib模块。email.encoders模块是email模块的一部分,它提供了对附件进行编码的功能。下面是一个使用email.encoders模块发送带有附件的邮件的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# 邮件发送者和接收者的信息
sender = "your_email@gmail.com"
receiver = "recipient_email@gmail.com"
# 创建MIMEMultipart对象,用于构建邮件内容
msg = MIMEMultipart()
# 设置邮件的主题和发送者、接收者
msg['Subject'] = "带有附件的邮件"
msg['From'] = sender
msg['To'] = receiver
# 设置邮件正文内容
body = "这是一封带有附件的邮件,请查收。"
msg.attach(MIMEText(body, 'plain'))
# 读取附件文件
filename = "attachment.txt"
attachment = open(filename, "rb")
# 创建MIMEBase对象,并将附件内容添加到MIMEBase对象中
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# 将附件添加到邮件中
msg.attach(part)
# 发送邮件
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "your_password") # 这里填写发送邮件的密码或者授权码
server.sendmail(sender, receiver, msg.as_string())
server.quit()
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:" + str(e))
在这个例子中,首先导入了smtplib、MIMEMultipart、MIMEText和MIMEBase等模块。然后设置了邮件的发送者和接收者信息,并创建了一个MIMEMultipart对象用于构建邮件内容。接下来设置了邮件的主题和正文内容,并将正文内容添加到MIMEMultipart对象中。
然后,读取了要发送的附件文件,并创建了一个MIMEBase对象。将附件的内容添加到MIMEBase对象中,并对附件进行编码。最后,将附件添加到MIMEMultipart对象中,并发送邮件。
在这个示例代码中,需要将sender和receiver变量设置为实际的邮件发送者和接收者的邮箱地址。还需要将filename和"your_password"变量分别设置为实际的附件文件名和发送邮件的密码或者授权码。
这就是使用email.encoders模块发送带有附件的邮件的示例代码。希望对你有帮助!
