python发送邮件(带附件)、发送给多人、抄送给多人的示例

  1. #!/usr/bin/env python  
  2. # -*-encoding: utf-8 -*-  
  3.   
  4.   
  5. import smtplib  
  6. from email.mime.multipart import MIMEMultipart  
  7. from email.mime.text import MIMEText  
  8.   
  9. #image包可以发送图片形式的附件  
  10. # from email.mime.image import MIMEImage  
  11.   
  12. # 可以查询文件对应的'Content-Type'  
  13. # import mimetypes  
  14. # mimetypes.guess_type('c:\\users\\adminstrator\\desktop\\ceshi.xls')  
  15.   
  16.   
  17. asender = '[email protected]'  
  18. #多个收件人用逗号隔开  
  19. areceiver = '[email protected][email protected]'  
  20. acc = '[email protected][email protected]'  
  21. asubject = u'HI'  
  22.   
  23. #阿里云邮箱的smtp服务器  
  24. asmtpserver = 'smtp.mxhichina.com'  
  25. ausername = '[email protected]'  
  26. apassword = '123456'  
  27.   
  28. #下面的to\cc\from最好写上,不然只在sendmail中,可以发送成功,但看不到发件人、收件人信息  
  29. msgroot = MIMEMultipart('related')  
  30. msgroot['Subject'] = asubject  
  31. msgroot['to'] = areceiver  
  32. msgroot['Cc'] = acc  
  33. msgroot['from'] = asender  
  34.   
  35. # MIMEText有三个参数,第一个对应文本内容,第二个对应文本的格式,第三个对应文本编码  
  36. thebody = MIMEText(u'Please check the attachment, thanks!''plain''utf-8')  
  37. msgroot.attach(thebody)  
  38.   
  39. # 读取xls文件作为附件,open()要带参数'rb',使文件变成二进制格式,从而使'base64'编码产生作用,否则附件打开乱码  
  40. # att = MIMEText(open('C:\\ceshi.xls', 'rb').read(), 'base64', 'GB2312')  
  41. # att['Content-Type'] = 'application/vnd.ms-excel'  
  42. # att['Content-Disposition'] = 'attachment; filename ="1.xls"'  
  43.   
  44. # 读取xlsx文件作为附件,open()要带参数'rb',使文件变成二进制格式,从而使'base64'编码产生作用,否则附件打开乱码  
  45. att = MIMEText(open(u'C:\\ceshi.xlsx''rb').read(), 'base64''utf-8')  
  46. att['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'  
  47. #下面的filename 等号(=)后面好像不能有空格  
  48. attname ='attachment; filename ="123.xlsx"'  
  49. att['Content-Disposition'] = attname  
  50.   
  51. msgroot.attach(att)  
  52.   
  53. asmtp = smtplib.SMTP()  
  54. asmtp.connect(asmtpserver)  
  55. asmtp.login(ausername, apassword)  
  56.   
  57. #发送给多人时,收件人应该以列表形式,areceiver.split把上面的字符串转换成列表  
  58. #只要在sendmail中写好发件人、收件人,就可以发送成功  
  59. # asmtp.sendmail(asender, areceiver.split(','), msgroot.as_string())  
  60.   
  61. #发送给多人、同时抄送给多人,发送人和抄送人放在同一个列表中  
  62. asmtp.sendmail(asender, areceiver.split(',') + acc.split(','), msgroot.as_string())  
  63. asmtp.quit() 

猜你喜欢

转载自blog.csdn.net/captain_mxd/article/details/79447666