python发送邮件的例子(带附件,html格式)

发布时间:2020-11-07编辑:脚本学堂
python 发送邮件的实现代码,可以发送带附件的邮件,以及html格式的邮件,smtplib模块用于python发送邮件功能的实现,效果不错。

专题教程:python发送邮件实例教程

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邮件,可以参考如下例子:
 

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)