返回列表 发帖

python+gmail+png+embed

python program for sending email with png embedded.
  1. #!/usr/bin/python

  2. import smtplib
  3. from email.MIMEMultipart import MIMEMultipart
  4. from email.MIMEText import MIMEText
  5. from email.MIMEImage import MIMEImage

  6. # Define these once; use them twice!
  7. strFrom = 'rex@zhasm.com'
  8. strTo = 'pig@zhasm.com'

  9. # Create the root message and fill in the from, to, and subject headers
  10. msgRoot = MIMEMultipart('related')
  11. msgRoot['Subject'] = 'test message'
  12. msgRoot['From'] = strFrom
  13. msgRoot['To'] = strTo
  14. msgRoot.preamble = 'This is a multi-part message in MIME format.'

  15. # Encapsulate the plain and HTML versions of the message body in an
  16. # 'alternative' part, so message agents can decide which they want to display.
  17. msgAlternative = MIMEMultipart('alternative')
  18. msgRoot.attach(msgAlternative)

  19. msgText = MIMEText('This is the alternative plain text message.')
  20. msgAlternative.attach(msgText)

  21. # We reference the image in the IMG SRC attribute by the ID we give it below
  22. msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
  23. msgAlternative.attach(msgText)

  24. # This example assumes the image is in the current directory
  25. fp = open('20091228_193344.png', 'rb')
  26. msgImage = MIMEImage(fp.read())
  27. fp.close()

  28. # Define the image's ID as referenced above
  29. msgImage.add_header('Content-ID', '<image1>')
  30. msgRoot.attach(msgImage)


  31. server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
  32. server.ehlo()
  33. server.starttls()
  34. server.ehlo()
  35. server.login('zhasm64@gmail.com','******')
  36. server.sendmail('rex@zhasm.com','pig@zhasm.com',msgRoot.as_string())
  37. server.close()
复制代码

返回列表