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

Asked

Viewed 1,543 times

4

When I send a simple Python email using only the smtplib library, I can write in the body of the email through the "message" argument of the following 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 attached email, I have to use the email library. An example of sending an image 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?

  • There are two well-voted answers here that might help: http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python

  • Well, it’s not duplicate per se, But in my answer to your other question (http://answall.com/questions/178078/como-enviar-um-arquivo-comor-anexo-por-e-mail-sem-que-ele-seja-automaticamente-re) you have exactly that. You lacked a little attention on your part. :)

1 answer

1


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

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 storing the body of the email.

def mensagem(string):
    from email.mime.text import MIMEText
    mime=MIMEText(string)
    return mime

Browser other questions tagged

You are not signed in. Login or sign up in order to post.