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
– Miguel
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. :)
– Luiz Vieira