Python-GMail-SMTP示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-GMail-SMTP示例相关的知识,希望对你有一定的参考价值。

  1. import os
  2. import smtplib
  3. import mimetypes
  4. from email.MIMEMultipart import MIMEMultipart
  5. from email.MIMEBase import MIMEBase
  6. from email.MIMEText import MIMEText
  7. from email.MIMEAudio import MIMEAudio
  8. from email.MIMEImage import MIMEImage
  9. from email.Encoders import encode_base64
  10.  
  11. def sendMail(subject, text, *attachmentFilePaths):
  12. gmailUser = '[email protected]'
  13. gmailPassword = 'bogus!'
  14. recipient = '[email protected]'
  15.  
  16. msg = MIMEMultipart()
  17. msg['From'] = gmailUser
  18. msg['To'] = recipient
  19. msg['Subject'] = subject
  20. msg.attach(MIMEText(text))
  21.  
  22. for attachmentFilePath in attachmentFilePaths:
  23. msg.attach(getAttachment(attachmentFilePath))
  24.  
  25. mailServer = smtplib.SMTP('smtp.gmail.com', 587)
  26. mailServer.ehlo()
  27. mailServer.starttls()
  28. mailServer.ehlo()
  29. mailServer.login(gmailUser, gmailPassword)
  30. mailServer.sendmail(gmailUser, recipient, msg.as_string())
  31. mailServer.close()
  32.  
  33. print('Sent email to %s' % recipient)
  34.  
  35. def getAttachment(attachmentFilePath):
  36. contentType, encoding = mimetypes.guess_type(attachmentFilePath)
  37.  
  38. if contentType is None or encoding is not None:
  39. contentType = 'application/octet-stream'
  40.  
  41. mainType, subType = contentType.split('/', 1)
  42. file = open(attachmentFilePath, 'rb')
  43.  
  44. if mainType == 'text':
  45. attachment = MIMEText(file.read())
  46. elif mainType == 'message':
  47. attachment = email.message_from_file(file)
  48. elif mainType == 'image':
  49. attachment = MIMEImage(file.read(),_subType=subType)
  50. elif mainType == 'audio':
  51. attachment = MIMEAudio(file.read(),_subType=subType)
  52. else:
  53. attachment = MIMEBase(mainType, subType)
  54. attachment.set_payload(file.read())
  55. encode_base64(attachment)
  56.  
  57. file.close()
  58.  
  59. attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath))
  60. return attachment

以上是关于Python-GMail-SMTP示例的主要内容,如果未能解决你的问题,请参考以下文章

Python学习示例源码

python实战应用讲解-numpy专题篇实用小技巧(附python示例代码)

python图形GUI基本示例

Joe 的 Erlang websocket 示例的 Python 示例

2018-06-20 中文代码示例视频演示Python入门教程第三章 简介Python

python错误示例