python smtplib attachment pdf code example
Example: smtplib send pdf
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
from socket import gethostname
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'])
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = '[email protected]'
msg['To'] = destination
msg.attach(MIMEText(message, "plain"))
with open(path_to_pdf, "rb") as f:
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
server.send_message(msg)