【6】网络与网页-3-SMTP发送邮件--smtplib、email

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

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

 一、纯文本邮件

from email.mime.text import MIMEText
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')

注意到构造MIMEText对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入’plain’,最终的MIME就是’text/plain’,最后一定要用utf-8编码保证多语言兼容性。

二、SMTP发出去

import smtplib

from_addr = your_email
password =your_email_password
smtp_server = "smtp.qiye.163.com" #<span style="color: #ff0000;">your email send server
to_addr =you_want_to_addr

server=smtplib.SMTP()
server.connect(smtp_server)
server.login(from_addr,password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()
print "your result has sent to your email!"

由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str

三、构建邮件主题

我们必须把From、To和Subject添加到MIMEText中,才是一封完整的邮件 msg[‘To’]接收的是字符串而不是list,如果有多个邮件地址,用,分隔即可。

四、添加附件

可以构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象即可:

五、例子

#!/usr/bin/python

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

from email.utils import parseaddr, formataddr

name=who_your_email_send

from_addr = your_email
password =your_email_password
smtp_server = "smtp.qiye.163.com"   #your email send server
to_addr =you_want_to_addr

msg = MIMEMultipart()

msg2 = MIMEText('Dear %s\n      We are  glad you use our company product,your result is in attachment! '%name, 'plain', 'utf-8')
msg['From'] =from_addr
msg['To'] =to_addr
msg['Subject'] ='GenoPrimer result'
msg.attach(msg2)

att1 = MIMEText(open('result/result', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="your.result"'
msg.attach(att1)

try:
    server=smtplib.SMTP()
    server.connect(smtp_server)
    server.login(from_addr,password)
    server.sendmail(from_addr,to_addr,msg.as_string())
    server.quit()
    print "your result has sent to your email!"
except Exception,e:
    print str(e)

参考资料:

http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html

http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000

个人公众号,比较懒,很少更新,可以在上面提问题:

更多精彩,请移步公众号阅读:

Sam avatar
About Sam
专注生物信息 专注转化医学