How to attach an image to an email, using the smtplib python library

0

What should I modify / add so that this piece of code can send attached images?

def send_email(usuario,paswor,correo):

  try:
    server=smtplib.SMTP("smtp.gmail.com:587")
    server.ehlo()
    server.starttls()
    server.login(config.EMAIL_ADDRES,config.PASSWORD)
    server.sendmail(config.EMAIL_ADDRES,correo)
    server.quit()
    print("E-Mail enviado con éxito")

except:
    print("ERROR AL ENVIAR EL MENSAGE")

Greetings and thank you very much.

    
asked by Diego 27.08.2018 в 22:23
source

1 answer

3

Here I have a code to send image to an email through that library in Python. I will place the complete code for you to review and compare:

# Importamos librerías
import smtplib
import mimetypes

# Importamos los módulos necesarios
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64

# Creamos objeto Multipart, quien será el recipiente que enviaremos
msg = MIMEMultipart()
msg['From']="[email protected]"
msg['To']="[email protected]"
msg['Subject']="Correo con imagen Adjunta"

# Adjuntamos Imagen
file = open("fondo.jpg", "rb")
attach_image = MIMEImage(file.read())
attach_image.add_header('Content-Disposition', 'attachment; filename = "avatar.png"')
msg.attach(attach_image)

# Autenticamos
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login("[email protected]","pasword")

# Enviamos
mailServer.sendmail("[email protected]", "[email protected]", msg.as_string())

# Cerramos conexión
mailServer.close()
    
answered by 27.08.2018 в 22:41