Skip to content

Instantly share code, notes, and snippets.

@tmasjc
Last active October 20, 2020 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmasjc/decdf9c4d0658f70f7de841c2fd7f56e to your computer and use it in GitHub Desktop.
Save tmasjc/decdf9c4d0658f70f7de841c2fd7f56e to your computer and use it in GitHub Desktop.
Sending email with attachment thru Python
# %%
import configparser
import pandas as pd
import smtplib
from socket import gaierror
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
config = configparser.ConfigParser()
config.read("config.ini")
mail = config["mail"]
smtp_server = mail["server"]
port = int(mail["port"])
login = mail["sender"]
password = mail["password"]
sender = login
receiver = login
subject = "Hello World"
body = "Testing from Python. Check attachment."
message = MIMEMultipart()
message["From"] = sender
message["To"] = receiver
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
filename = config["output"]["path"]
# %%
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename= {filename}")
message.attach(part)
text = message.as_string()
# %%
try:
with smtplib.SMTP_SSL(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, text)
# feedback something
print('Sent')
except (gaierror, ConnectionRefusedError):
print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment