Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sendmail with Attachment?

I am programming with python. I already have a function that sends mails with attachments, but the problem is that it takes the message and puts it as an attachment. I need that it respects the message as message and the attachment as attachment. I have investigated and I found that has to do with MIME Multipart "MIXED" but i don't know how to add or change this to my actual functions.

Here is the python code of the function I am using:

def enviarCorreo(fromaddr, toaddr, file):
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'asunto'
    #adjunto
    adjunto = MIMEBase('application', "octet-stream")
    adjunto.set_payload(open(file, "rb").read())
    encode_base64(adjunto)
    adjunto.add_header('Content-Disposition', 'attachment; filename= "%s"' % file)
    msg.attach(adjunto)
    #enviar
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.quit()
    return
like image 396
mauguerra Avatar asked Jul 26 '26 03:07

mauguerra


1 Answers

You forgot to attach the text as msg.attach( MIMEText(text) )

def enviarCorreo(fromaddr, toaddr, text, file):
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'asunto'

    #This is the part you had missed.
    msg.attach( MIMEText(text) )

    #adjunto
    adjunto = MIMEBase('application', "octet-stream")
    adjunto.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(adjunto)
    adjunto.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(adjunto)

    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.close()

enviarCorreo("[email protected]", ["[email protected]"], "Hello World", ['/tmp/sample.png'])

See if this works for you.

like image 152
meson10 Avatar answered Jul 27 '26 16:07

meson10