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?