Advertisement
Guest User

Untitled

a guest
May 18th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import smtplib
  4. import csv
  5. import getpass
  6.  
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.text import MIMEText
  9.  
  10.  
  11. def write_msg(fname, sender, receiver):
  12. """ Write a message"""
  13. # Message container
  14. msg = MIMEMultipart('alternative')
  15. msg['Subject'] = "SUBJECT"
  16. msg['From'] = sender
  17. msg['To'] = receiver
  18.  
  19. # Body of message
  20. text = "Text".format(fname)
  21.  
  22. html = """\
  23. <html>
  24. <head></head>
  25. <body>
  26.  
  27. </body>
  28. </html>""".format(fname)
  29.  
  30. # Record the MIME types of both parts - text/plain and text/html.
  31. part1 = MIMEText(text, 'plain')
  32. part2 = MIMEText(html, 'html')
  33.  
  34. msg.attach(part1)
  35. msg.attach(part2)
  36.  
  37. return msg
  38.  
  39.  
  40. def main():
  41. """Main"""
  42. # SMTP server connection settings
  43. server = 'smtp.server.com:587'
  44. smtp_user = 'USER'
  45. smtp_pwd = getpass.getpass("Enter your SMTP server password:")
  46. sender = 'SENDER'
  47.  
  48. # Data file
  49. fn = ('xxx.csv')
  50.  
  51. # Read in account information
  52. csvfile = open(fn, "rb")
  53. reader = csv.reader(csvfile)
  54. reader.next()
  55. data = [row for row in reader]
  56. csvfile.close()
  57. snd_email = raw_input("Send email/s y or n:")
  58. if snd_email == "y":
  59. try:
  60. smtpserver = smtplib.SMTP(server)
  61. smtpserver.ehlo()
  62. smtpserver.starttls()
  63. smtpserver.ehlo
  64. smtpserver.login(smtp_user, smtp_pwd)
  65. except smtplib.SMTPException:
  66. print "Error: unable to connect to SMTP server"
  67.  
  68. for fname, lname, email in data:
  69. receiver = ' '.join([fname, lname, ''.join(['<', email, '>'])])
  70. print "Message to {0}".format(receiver)
  71. msg = write_msg(fname, sender, receiver)
  72. try:
  73. smtpserver.sendmail(sender, receiver, msg.as_string())
  74. print "Successfully sent email"
  75. except smtplib.SMTPException:
  76. print "Error: unable to send email"
  77.  
  78. smtpserver.close()
  79.  
  80.  
  81. if __name__ == "__main__":
  82. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement