使用Python的email.mime.text模块创建带有附件的纯文本邮件
发布时间:2023-12-24 01:11:58
下面是使用Python的email.mime.text模块创建带有附件的纯文本邮件的示例代码:
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 = "<sender_email>"
receiver = "<receiver_email>"
# 创建包含邮件内容的MIMEMultipart对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = "带附件的纯文本邮件"
# 邮件正文
body = "这是一封带有附件的纯文本邮件。"
msg.attach(MIMEText(body, 'plain'))
# 附件文件路径
attachment_path = "<attachment_file_path>"
# 创建MIMEBase对象处理附件
attachment = open(attachment_path, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
# 将附件内容转换为base64
encoders.encode_base64(part)
# 添加附件标题和内容类型
part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path)
msg.attach(part)
# 发送邮件
smtp_server = "smtp.<domain>.com"
smtp_port = 587
# 登录邮箱
username = "<email_username>"
password = "<email_password>"
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(sender, receiver, msg.as_string())
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", str(e))
finally:
server.quit()
请注意,上述代码中的 <sender_email>, <receiver_email>, <attachment_file_path>, <domain>, <email_username>, <email_password> 应根据实际情况进行替换。
