m0n0lithic

Python: Send email + Attachment via MIMEMultipart

Aug 19th, 2014
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from time import localtime
  3. import smtplib, os
  4. from email.MIMEMultipart import MIMEMultipart
  5. from email.MIMEBase import MIMEBase
  6. from email.MIMEText import MIMEText
  7. from email.Utils import COMMASPACE, formatdate
  8. from email import Encoders
  9.  
  10. def send_mail(send_from, send_to, send_bcc, subject, text, files=[], server="localhost"):
  11.     assert isinstance(send_to, list)
  12.     assert isinstance(send_bcc, list)
  13.     assert isinstance(files, list)
  14.     msg = MIMEMultipart()
  15.     msg['From'] = send_from
  16.     msg['To'] = COMMASPACE.join(send_to)
  17.     #msg['BCC'] = COMMASPACE.join(send_bcc)
  18.     msg['Date'] = formatdate(localtime=True)
  19.     msg['Subject'] = subject
  20.     msg.attach( MIMEText(text) )
  21.     for f in files:
  22.         part = MIMEBase('application', "octet-stream")
  23.         part.set_payload( open(f,"rb").read() )
  24.         Encoders.encode_base64(part)
  25.         part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
  26.         msg.attach(part)
  27.     USERNAME = "Wilderman.xxxxx"
  28.     PASSWORD = "m0nxxxxxx"
  29.     smtp = smtplib.SMTP(server)
  30.     smtp.ehlo()
  31.     smtp.starttls()
  32.     smtp.ehlo()
  33.     smtp.set_debuglevel(False)
  34.     smtp.login(USERNAME, PASSWORD)
  35.     try:
  36.         smtp.sendmail(send_from, [send_to,send_bcc], msg.as_string())
  37.     finally:
  38.         smtp.close()
  39.     #smtp.sendmail(send_from, send_to, msg.as_string())
  40.     #smtp.close()
  41.  
  42.  
  43. if __name__ == '__main__':
  44.     HORA_SYS = localtime()
  45.     year = str(HORA_SYS[0])
  46.     mont = str(HORA_SYS[1]).zfill(2)
  47.     day = str(HORA_SYS[2]).zfill(2)
  48.     sender = 'Servicio de datos SPOA <[email protected]>'
  49.     to = ['xxxxx@xxxxx']
  50.     bcc = ['[email protected]']
  51.     subject = "::.SPOA.:: Vientos Puerto Bolivar ["+year+mont+day+"]"
  52.     files = ['/spoa/scripts/matlab/anemografos/wind_'+year+mont+day+'.dat']
  53.     send_mail(sender, to, bcc, subject, 'Saludos.\nAdjunto archivo de vientos para Puerto Bolivar correspondiente al '+ year+mont+day, files, "172.25.1.63")
Advertisement
Add Comment
Please, Sign In to add comment