Python基于smtplib模块发送邮件的代码详解-创新互联-成都快上网建站

Python基于smtplib模块发送邮件的代码详解-创新互联

这篇文章主要讲解了Python基于smtplib模块发送邮件的代码详解,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

创新互联主营思礼网站建设的网络公司,主营网站建设方案,手机APP定制开发,思礼h5小程序定制开发搭建,思礼网站营销推广欢迎思礼等地区企业咨询

smtplib模块负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。

email模块负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。

email模块下有mime包,mime英文全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范。

该mime包下常用的有三个模块:text,image,multpart。

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 attach2。\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 attach2。\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'

attach2 = MIMEText(open(attach_file1, 'rb').read(), 'base64', 'utf-8')
attach2["Content-Type"] = 'application/octet-stream'
attach2["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file1)
message.attach(attach2)

# 构造附件2
attach_file2='YLJ.jpg'
attach3 = MIMEText(open(attach_file2, 'rb').read(), 'base64', 'utf-8')
attach3["Content-Type"] = 'application/octet-stream'
attach3["Content-Disposition"] = 'attachment; filename={0}'.format(attach_file2)
message.attach(attach3)

# 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()

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


名称栏目:Python基于smtplib模块发送邮件的代码详解-创新互联
链接地址:http://kswjz.com/article/cohjig.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流