Send mail to Gmail programatically with Python

  1. #!/usr/bin/python
  2.  
  3. import smtplib
  4. from email.MIMEMultipart import MIMEMultipart
  5. from email.MIMEBase import MIMEBase
  6. from email.MIMEText import MIMEText
  7. from email import Encoders
  8. import os
  9.  
  10. gmail_user = "xyz@gmail.com"
  11. gmail_pwd = "*******"
  12.  
  13. def mail(to, subject, text,
  14. attach=[]):
  15. msg = MIMEMultipart()
  16.  
  17. msg['From'] = gmail_user
  18. msg['To'] = to
  19. msg['Subject'] = subject
  20.  
  21. msg.attach(MIMEText(text))
  22.  
  23. for file in files:
  24. part = MIMEBase('application', "octet-stream")
  25. part.set_payload( open(file,"rb").read() )
  26. Encoders.encode_base64(part)
  27. part.add_header('Content-Disposition', 'attachment; filename="%s"'
  28. % os.path.basename(file))
  29. msg.attach(part)
  30.  
  31.  
  32. mailServer = smtplib.SMTP("smtp.gmail.com", 587)
  33. mailServer.ehlo()
  34. mailServer.starttls()
  35. mailServer.ehlo()
  36. mailServer.login(gmail_user, gmail_pwd)
  37. mailServer.sendmail(gmail_user, to, msg.as_string())
  38. mailServer.close()
  39.  
  40. mail("xyz@example.com",
  41. "Hello from python!",
  42. "This is a email sent with python",
  43. "attachment1","attachment2")

0 comments on Send mail to Gmail programatically with Python

    Post new comment

    • Web page addresses and e-mail addresses turn into links automatically.
    • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
    • Lines and paragraphs break automatically.

    More information about formatting options

Drupal SEO