邮件模块

Posted dxnui119

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了邮件模块相关的知识,希望对你有一定的参考价值。

SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、html邮件以及带附件的邮件。

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。SMTP协议就是简单的文本命令和响应。

login()方法用来登录SMTP服务器,sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str。

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = test@xx.com
receiver = [xx1@126.com,xx2@126.com]
subject = test
smtpserver = mail.xx.com
smtpport = 25
username = user1@xx.com
password = password123
context = haha

构造MIMEText对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入‘plain‘,最终的MIME就是‘text/plain‘,使用utf-8编码。

msg = MIMEText(context, plain, utf-8)
msg[Subject] = Header(subject, utf-8)

smtp = smtplib.SMTP()

smtp.connect(smtpserver,smtpport)
smtp.set_debuglevel(1) 
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()

 

以上是关于邮件模块的主要内容,如果未能解决你的问题,请参考以下文章