m0n0lithic icon

Python: Send email + Attachment via MIMEMultipart (Exchange)

m0n0lithic | PRO | 08/20/14 09:38:31 PM UTC | 0 ⭐ | 518 👁️ | Never ⏰ | []
Python |

2.01 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python
from time import localtime
import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
 
def send_mail(send_from, send_to, send_bcc, subject, text, files=[], server="localhost"):
    assert isinstance(send_to, list)
    assert isinstance(send_bcc, list)
    assert isinstance(files, list)
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    #msg['BCC'] = COMMASPACE.join(send_bcc)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach( MIMEText(text) )
    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)
    USERNAME = "Wilderman.xxxxx"
    PASSWORD = "m0nxxxxxx"
    smtp = smtplib.SMTP(server)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.set_debuglevel(False)
    smtp.login(USERNAME, PASSWORD)
    try:
        smtp.sendmail(send_from, [send_to,send_bcc[0], send_bcc[1]], msg.as_string())
    finally:
        smtp.close()
    #smtp.sendmail(send_from, send_to, msg.as_string())
    #smtp.close()
 
 
if __name__ == '__main__':
    HORA_SYS = localtime()
    year = str(HORA_SYS[0])
    mont = str(HORA_SYS[1]).zfill(2)
    day = str(HORA_SYS[2]).zfill(2)
    sender = 'Servicio de datos SPOA <[email protected]>'
    to = ['xxxxx@xxxxx']
    bcc = ['[email protected]', '[email protected]']
    subject = "::.SPOA.:: Vientos Puerto Bolivar ["+year+mont+day+"]"
    files = ['/spoa/scripts/matlab/anemografos/wind_'+year+mont+day+'.dat']
    send_mail(sender, to, bcc, subject, 'Saludos.\nAdjunto archivo de vientos para Puerto Bolivar correspondiente al '+ year+mont+day, files, "172.25.1.63")

Comments