Python使用smtplib和email模块发送带附件邮件的完整示例
本文介绍如何使用Python的smtplib模块连接邮箱服务器发送邮件,以及利用email模块构造包含发件人、收件人、主题、正文和附件的完整邮件结构。通过MIMEMultipart处理多媒体内容,结合代码实例演示如何成功发送包含图片附件的邮件,适用于需要自动化邮件通知或文件传输的场景。
Python发送邮件的核心模块介绍
smtplib模块主要用于执行发送邮件的操作,其核心功能包括连接邮箱服务器、登录邮箱账户,以及将包含发件人、收信人和邮件内容的邮件发送出去。
email模块则负责邮件内容的构造,具体涉及在邮箱页面中显示的各项元素,例如发件人、收件人、邮件主题、正文内容以及附件等。
email模块下包含mime包,mime的全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,这是目前互联网电子邮件普遍遵循的技术规范。
在mime包中,常用的模块主要有三个:text、image和multpart。
Python发送带附件邮件的代码实现
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#邮件服务器信息
smtp_server = "smtp.qq.com"
port = 465 # For starttls
sender_email = "12345689@qq.com"
password="" #get password from mailsetting
#发送邮件信息,可以发送给多个收件人
receivers=["12345689@163.com","12345689@qq.com"]
subject="This is import Python SMTP 邮件(文件传输) 多媒体测试"
# message = MIMEText(text, "plain", "utf-8") #文本邮件
message = MIMEMultipart()
message["Subject"] = Header(subject, "utf-8")
message["from"] = sender_email
message["to"] = ",".join(receivers)
# 邮件正文内容
text="""
Dear Sir:
how are you ? \n
for detail information pls refer to attach1。\n
The files you need are as followed.\n
If you have any concern pls let me known.\n
enjoy your weekend.\n
BEST REGARDS \n
"""
# message.attach(MIMEText('for detail information pls refer to attach1。\n The files you need are as followed. \n If you have any concern pls let me known. \n enjoy your weekend', 'plain', 'utf-8')
message.attach(MIMEText(text,'plain','utf-8'))
# 构造附件1
attach_file1='IMG1965.JPG'
attach1 = MIMEText(open(attach_file1, 'rb').read(), 'base64', 'utf-8')
attach1["Content-Type"] = 'application/octet-stream'
attach1["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file1)
message.attach(attach1)
# 构造附件2
attach_file2='YLJ.jpg'
attach2 = MIMEText(open(attach_file2, 'rb').read(), 'base64', 'utf-8')
attach2["Content-Type"] = 'application/octet-stream'
attach2["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file2)
message.attach(attach2)
# Try to log in to server and send email
# server = smtplib.SMTP_SSL(smtp_server,port)
server = smtplib.SMTP_SSL(smtp_server,port)
try:
server.login(sender_email, password)
server.sendmail(sender_email,receivers,message.as_string())
print("邮件发送成功!!!")
print("Mail with {0} & {1} has been send to {2} successfully.".format(attach_file1,attach_file2,receivers))
except Exception as e:
# Print any error messages to stdout
print("Error: 无法发送邮件")
print(e)
finally:
server.quit()
邮件发送结果验证
运行结果
邮件发送成功!!!
Mail with IMG1965.JPG & IMG1963.jpg has been send to ['12345689@163.com', '12345689@qq.com'] successfully.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













