Solución:
En este caso, crea un mensaje con un paquete de correo electrónico:
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))
y luego envíe el mensaje.
import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
Varios ejemplos aquí: http://docs.python.org/library/email-examples.html
ACTUALIZAR
Actualizar el enlace desde lo anterior produce un 404 https://docs.python.org/2/library/email-examples.html. Gracias @Tshirtman
Update2: la forma más sencilla de adjuntar pdf
Para adjuntar el pdf
usa la bandera pdf:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('[email protected]', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspiraciones / créditos para: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
La forma recomendada es usar Python Email módulo para componer mensajes MIME con el formato adecuado. Ver documentos
Para python 2
https://docs.python.org/2/library/email-examples.html
Para python 3
https://docs.python.org/3/library/email.examples.html
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)