How to send email with body and attachment using smtplib and email in python?

4

When I send a simple email in Python using only the smtplib library, I can type in the email body through the "message" argument of the script function:

def enviaremail(usuario,senha,mensagem,listadestinatarios):
    from smtplib import SMTP
    smtp=SMTP('smtp.live.com',587)
    smtp.starttls()
    smtp.login(usuario,senha)
    smtp.sendmail(usuario,listadestinatarios,mensagem)
    smtp.quit()
    print('E-mail enviado com sucesso')
enviaremail('[email protected]','xxxx','ola mundo',['[email protected]']

However, when I send an email with an attachment, I have to use the email library. An example of sending an e-mail as an attachment is:

def enviaremail(usuario,senha,mensagem,listadestinatarios):
    from smtplib import SMTP
    smtp=SMTP('smtp.live.com',587)
    smtp.starttls()
    smtp.login(usuario,senha)
    smtp.sendmail(usuario,listadestinatarios,mensagem)
    smtp.quit()
    print('E-mail enviado com sucesso')
def anexoimagem(path):
    from email.mime.image import MIMEImage
    with open(path,'rb') as f:
        mime=MIMEImage(f.read(),subtype='jpg')
    return mime
msg=anexoimagem('foto.jpg')
msg['From']='[email protected]'
msg['To']='[email protected]'
msg['Subject']='testando mensagem com anexo'
enviaremail('[email protected]','xxxx',msg.as_string,['[email protected]']

The problem is that the message becomes the attachment, not the body of the email, as in the previous case. The question is: how can I add a body to the email in this second script? How to send an email with body and attachment together?

    
asked by anonymous 17.01.2017 / 18:12

1 answer

1

After searching more, I discovered that the MIMEText object, in addition to storing text attachments, can also store the body of the email. The following function returns a MIME object by storing a .txt file.

def anexotexto(path):
    from email.mime.text import MIMEText
    with open(path,'r') as f:
        mime=MIMEText(f.read(),_subtype='txt')
    return mime

The following function returns a MIME object by storing the body of the email.

def mensagem(string):
    from email.mime.text import MIMEText
    mime=MIMEText(string)
    return mime
    
17.01.2017 / 23:35