用python发送邮件需要引入smtp(smtplib.smtp)包,如果要发送复杂邮件,可以用email包。
1、smtplib包发送邮件
smtplib包中的核心类:smtplib.SMTP、smtplib.SMTP_SSL等。
构造SMTP:
发送邮件:
参数中的msg是Message对象(email.message.Message)。
2、email包发送邮件
Message类是email包的核心,它位于email.message模块。
email包提供了多种不同类型的MIME对象,它们分别是:
这些对象的继承关系:
MIMEBase
|-- MIMENonMultipart
|-- MIMEApplication
|-- MIMEAudio
|-- MIMEImage
|-- MIMEMessage
|-- MIMEText
|-- MIMEMultipart
最基础的MIMEBase则继承自Message。通常而言无需直接使用MIMEBase,而应该使用这些继承类。
MIMENonMultipart是中间层,它的主要作用就是阻止attach()的使用。
要使用attach(),则应该用MIMEMultipart。再看这些类的构造函数:
Python发送邮件实战
1、发送一份简单邮件:
import smtplib
if __name__ == "__main__":
host = "smtp.gmail.com"
port = 465
user = "SENDER@gmail.com"
pwd = "MYPASSWD"
s = smtplib.SMTP_SSL(host, port);
s.login(user, pwd)
s.sendmail(user, "RECEIVER@gmail.com", "hello, berlinix!")
查看邮箱,收到一封没有title的邮件,内容是hello, berlinix!
接下来为邮件添加title,并丰富下邮件内容,这次用HTML格式作为邮件内容。
代码:
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
if __name__ == "__main__":
host = "smtp.gmail.com"
port = 465
sender = "SENDER@gmail.com"
pwd = "MYPASSWD"
receiver = "RECEIVER@gmail.com"
body = "<h1>Welecome to Berlinix.com</h1>"
body += "<p>Here is my personal blog, include some technical notes.</p>"
msg = MIMEText(body, "html")
msg["subject"] = "Welcome to Berlinix.com"
msg["from"] = sender
msg["to"] = receiver
s = smtplib.SMTP_SSL(host, port);
s.set_debuglevel(1)
s.login(sender, pwd)
s.sendmail(sender, receiver, msg.as_string())
在邮件中内嵌一个图片并发送:
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
if __name__ == "__main__":
host = "smtp.gmail.com"
port = 465
sender = "SENDER@gmail.com"
pwd = "MYPASSWD"
receiver = "RECEIVER@gmail.com"
body = "<h1>Welecome to Berlinix.com</h1>"
body += "<p>Here is my personal blog, include some technical notes.</p>"
body += "<p><img src='cid:pylogo' />Python Programming Language</p>"
msg_root = MIMEMultipart("related")
msg_root["subject"] = "Welcome to Berlinix.com";
msg_root["from"] = sender
msg_root["to"] = receiver
msg_html = MIMEText(body, "html")
msg_root.attach(msg_html)
imgfp = open("python-logo.gif", "rb")
msg_img = MIMEImage(imgfp.read())
msg_img.add_header("Content-ID", "")
msg_img.add_header("Content-Disposition", "inline", filename="python-logo.gif")
msg_root.attach(msg_img)
s = smtplib.SMTP_SSL(host, port);
s.set_debuglevel(1)
s.login(sender, pwd)
s.sendmail(sender, receiver, msg_root.as_string())
以上代码使用了MIMEMultipart,并且创建了2个MIME对象msg_html和msg_img,并将他们attach()上msg_root。
以上注意嵌入图片的使用:<img src="cid:pylogo.gif">。
如果只为邮件添加附件,而不是嵌入图片,代码: