Question :
I’m a beginner in sending emails through a script and I’m having a problem. Use Python 3.5. When sending attachments with the following script, they lose the extension and are renamed:
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']='xxxx@hotmail.com'
msg['To']='xxxx@hotmail.com'
msg['Subject']='testando mensagem com anexo'
enviaremail('xxxx@hotmail.com','xxxx',msg.as_string,['xxxx@hotmail.com']
For example, the photo.jpg file appears as ATT0001 in the email. Renamed and without the .jpg extension it has. The same goes for text and audio files. How do I keep files filename and extension when sent as attachments?
Answer :
You are not setting the name of the attachment, so a generated name is being used. Try changing the line:
mime=MIMEImage(f.read(),subtype='jpg')
by:
mime=MIMEImage(f.read(),subtype='jpg', name=os.path.basename(path))
Of course, to use the basename
function you will need to import the os
package:
import os
You can also specify the name of the file in the MIME content header before calling enviaremail
:
msg.add_header('Content-Disposition', 'attachment', filename='foto.jpg')
See this example in the documentation.
Editing
Here is a small sample code that does just that: it reads an image of the file named "img.jpg"
and sends it in email as if its name were "Ó o auê aí, ô.jpg"
:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
smtp_server = '<seu servidor aqui>'
smtp_port = <porta>
acc_addr = '<seu email aqui>'
acc_pwd = '<sua senha aqui>'
to_addr = '<seu destinatário aqui>'
subject = 'Teste do SOPT!'
body = 'Este é um teste de envio de email via Python!'
# Configura o servidor de envio (SMTP)
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(acc_addr, acc_pwd)
# Cria o documento com várias partes
msg = MIMEMultipart()
msg["From"] = acc_addr
msg["To"] = to_addr
msg["Subject"] = subject
# Anexa a imagem
imgFilename = 'Ó o auê aí, ô.jpg' # Repare que é diferente do nome do arquivo local!
with open('img.jpg', 'rb') as f:
msgImg = MIMEImage(f.read(), name=imgFilename)
msg.attach(msgImg)
# Anexa o corpo do texto
msgText = MIMEText('<b>{}</b><br><img src="cid:{}"><br>'.format(body, imgFilename), 'html')
msg.attach(msgText)
# Envia!
server.sendmail(acc_addr, to_addr, msg.as_string())
server.quit()
Result: