python中使用smtplib模块发送email,smtp(simple mail transfer protocal),简单邮件传输协议,通过与smtp server通讯。
python smtplib模块例子:
 
#!/usr/bin/env python
#
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,两个模块:MIMEMultipart和MIMEText,可以利用它们构造和解析邮件信息。
代码:
 
#!/usr/bin/env python
#
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邮件,可以参考如下例子:
 
如果要发送附件,只要把附件attach到msg实例:
 
Send Email模板:
 
使用以上模板可以实现向多人发送,可添加附件。
问题,smtplib无法正确实现cc的功能,虽然有msg['Cc']模块,但不起作用(症状是在收到的邮件里确实有cc一栏,但cc里的人是收不到邮件的),这应该是smtplib的一个bug,目前找不到方法解决。
调用以上模板的客户端例子: