Python发送邮件实例

文件形式的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5. from email.header import Header  
  6.   
  7. sender = '***'  
  8. receiver = '***'  
  9. subject = 'python email test'  
  10. smtpserver = 'smtp.163.com'  
  11. username = '***'  
  12. passwor = '***'  
  13.   
  14. msg = MIMEText('你好','text','utf-8')#中文需参数‘utf-8’,单字节字符不需要  
  15. msg['Subject'] = Header(subject, 'utf-8')  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  

HTML形式的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.text import MIMEText  
  5.   
  6. sender = '***'  
  7. receiver = '***'  
  8. subject = 'python email test'  
  9. smtpserver = 'smtp.163.com'  
  10. username = '***'  
  11. passwor = '***'  
  12.   
  13. msg = MIMEText('<html><h1>你好</h1></html>','html','utf-8')  
  14.   
  15. msg['Subject'] = subject  
  16.   
  17. smtp = smtplib.SMTP()  
  18. smtp.connect('smtp.163.com')  
  19. smtp.login(username, password)  
  20. smtp.sendmail(sender, receiver, msg.as_string())  
  21. smtp.quit()  

带图片的HTML邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEImage  
  7.   
  8. sender = '***'  
  9. receiver = '***'  
  10. subject = 'python email test'  
  11. smtpserver = 'smtp.163.com'  
  12. username = '***'  
  13. passwor = '***'  
  14.   
  15. msgRoot = MIMEMultipart('related')  
  16. msgRoot['Subject'] = 'test message'  
  17.   
  18. msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>good!','html','utf-8')  
  19. msgRoot.attach(msgText)  
  20.   
  21. fp = open('h:\\python\\1.jpg', 'rb')  
  22. msgImage = MIMEImage(fp.read())  
  23. fp.close()  
  24.   
  25. msgImage.add_header('Content-ID', '<image1>')  
  26. msgRoot.attach(msgImage)  
  27.   
  28. smtp = smtplib.SMTP()  
  29. smtp.connect('smtp.163.com')  
  30. smtp.login(username, password)  
  31. smtp.sendmail(sender, receiver, msgRoot.as_string())  
  32. smtp.quit()  

带附件的邮件

  1. #!/usr/bin/env python3  
  2. #coding: utf-8  
  3. import smtplib  
  4. from email.mime.multipart import MIMEMultipart  
  5. from email.mime.text import MIMEText  
  6. from email.mime.image import MIMEIm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值