关于python写邮件各种功能我们已经介绍过很多,大家有兴趣可以参考:

python实现发送qq邮件(可加附件)

下面我们看下本次介绍的全部代码实例

import smtplib  
from email.mime.multipart import mimemultipart  
from email.mime.text import mimetext  
from email.mime.image import mimeimage 
from email.header import header  
  
#设置smtplib所需的参数
#下面的发件人,收件人是用于邮件传输的。
smtpserver = 'smtp.163.com'
username = 'xxx@163.com'
password='xxx'
sender='xxx@163.com'
#receiver='xxx@126.com'
#收件人为多个收件人
receiver=['xxx@126.com','xxx@126.com']
 
subject = 'python email test'
#通过header对象编码的文本,包含utf-8编码信息和base64编码信息。以下中文名测试ok
#subject = '中文标题'
#subject=header(subject, 'utf-8').encode()
  
#构造邮件对象mimemultipart对象
#下面的主题,发件人,收件人,日期是显示在邮件页面上的。
msg = mimemultipart('mixed') 
msg['subject'] = subject
msg['from'] = 'xxx@163.com <xxx@163.com>'
#msg['to'] = 'xxx@126.com'
#收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
msg['to'] = ";".join(receiver) 
#msg['date']='2012-3-16'
 
#构造文字内容  
text = "hi!\nhow are you?\nhere is the link you wanted:\nhttp://www.baidu.com"  
text_plain = mimetext(text,'plain', 'utf-8')  
msg.attach(text_plain)  
 
#构造图片链接
sendimagefile=open(r'd:\pythontest\testimage.png','rb').read()
image = mimeimage(sendimagefile)
image.add_header('content-id','<image1>')
image["content-disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image)
 
#构造html
#发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,报554 dt:spm :<p><img src="cid:image1"></p>
html = """
<html> 
 <head></head> 
 <body> 
  <p>hi!<br> 
    how are you?<br> 
    here is the <a href="http://www.baidu.com" rel="external nofollow" >link</a> you wanted.<br> 
  </p> 
 </body> 
</html> 
"""  
text_html = mimetext(html,'html', 'utf-8')
text_html["content-disposition"] = 'attachment; filename="texthtml.html"'  
msg.attach(text_html)  
 
 
#构造附件
sendfile=open(r'd:\pythontest11.txt','rb').read()
text_att = mimetext(sendfile, 'base64', 'utf-8') 
text_att["content-type"] = 'application/octet-stream' 
#以下附件可以重命名成aaa.txt 
#text_att["content-disposition"] = 'attachment; filename="aaa.txt"'
#另一种实现方式
text_att.add_header('content-disposition', 'attachment', filename='aaa.txt')
#以下中文测试不ok
#text_att["content-disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
msg.attach(text_att)  
    
#发送邮件
smtp = smtplib.smtp()  
smtp.connect('smtp.163.com')
#我们用set_debuglevel(1)就可以打印出和smtp服务器交互的所有信息。
#smtp.set_debuglevel(1) 
smtp.login(username, password)  
smtp.sendmail(sender, receiver, msg.as_string())  
smtp.quit()

www.887551.com测试后发现,这个实例可以把很多元素当做一个多文本编辑器,放在邮件附件里,非常好用。

以上就是python邮件中附加文字、html、图片、附件实现方法的详细内容,更多关于python邮件中添加元素附件方法的资料请关注www.887551.com其它相关文章!