在Python里我们可以使用smtplib模块发送email,smtp(Simple Mail Transfer Protocal),是简单邮件传输协议,通过它可以和smtp server进行通讯。
smtplib的一个简单例子
import smtplib
"""The first step is to create an SMTP object, each object is used for connection with one server."""
server = smtplib.SMTP('smtp.163.com','994')
#Next, log in to the server
server.login("username","password")
#Send the mail
msg = "\nHello!" # The \n separates the message from the headers
server.sendmail("from@163.com", "to@gmail.com", msg)
首先你要获得邮件服务器的smtp地址和端口号,一般都能在网上找到,然后输入你邮箱的用户名和密码,编辑邮件标题和正文(它们之间用\n隔开),最后指定目标邮件地址发送邮件。
使用Email Package
Python里有两个模块:MIMEMultipart和MIMEText,我们可以利用它们构造和解析邮件信息。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
#First, we compose some of the basic message headers:
fromaddr = "from@163.com"
toaddr = "to@gmail.com"
ccaddr = "cc@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Cc'] = ccaddr
msg['Subject'] = "Python email"
#Next, we attach the body of the email to the MIME message:
body = "Python test mail"
msg.attach(MIMEText(body, 'plain'))
'''For sending the mail, we have to convert the object to a string, and then
use the same prodecure as above to send using the SMTP server..'''
server = smtplib.SMTP('smtp.163.com','994')
server.login("username","password")
text = msg.as_string()server.sendmail(fromaddr, toaddr, text)
上面这个例子发送了一个纯文本信息(Plain),如果有发送html邮件,可以参考如下例子:
body = "<a href='http://blog.csdn.net/u010415792'>Zhu_Julian's Blog</a>"
msg.attach(MIMEText(body, 'html'))
如果要发送附件,只要把附件attach到msg实例即可:
#Attach an attachment
att = MIMEText(open(r'c:\123.txt', 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="123.txt'
msg.attach(att)
Send Email模板
#!/bin/python
# -*- coding: UTF-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE,formatdate
from email import encoders
import os
#server['name'],server['port'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]):
assert type(server) == dict
assert type(fro) == str
assert type(to) == list
assert type(subject) == str
assert type(text) == str
assert type(files) == list
msg = MIMEMultipart()
msg['From'] = fro
msg['Subject'] = subject
msg['To'] = COMMASPACE.join(to) #COMMASPACE==','
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text))
for file in files:
att = MIMEText(open(file, 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename = os.path.basename(file))
msg.attach(att)
import smtplib
smtp = smtplib.SMTP(server['name'],server['port'])
smtp.login(server['user'], server['passwd'])
smtp.sendmail(fro, to, msg.as_string())
smtp.close()
利用上面的模板可以实现向多人发送,可添加附件,但有一个问题,就是smtplib无法正确实现cc的功能,虽然有msg['Cc']模块,但不起作用(症状是在收到的邮件里确实有cc一栏,但cc里的人是收不到邮件的),这应该是smtplib的一个bug,目前找不到方法解决。
下面是调用上面模板的客户端例子:
server={'name':'smtp.163.com','port':'994','user':'mailuser','passwd':'mailpwd'}
fro='zhuxj@163.com'
to=['zhangxg@163.com','xjzhu86@gmail.com']
subject='Weekly Data - '+timemark
text='Docter Zhang, see attachment please.'
files=[efilename]
mymodule.send_mail(server,fro,to,subject,text,files)