Skip to content

Instantly share code, notes, and snippets.

@PeterJCLaw
Last active February 27, 2023 21:10
Show Gist options
  • Save PeterJCLaw/1d53eee245992e28509e81070f0ccaf9 to your computer and use it in GitHub Desktop.
Save PeterJCLaw/1d53eee245992e28509e81070f0ccaf9 to your computer and use it in GitHub Desktop.
Scripted email sending with attachments
#!/usr/bin/env python3
"""
Script to send emails with attachments, via gmail.
"""
# Based on a combination of:
# - https://stackoverflow.com/a/3363254/67873
# - https://github.com/PeterJCLaw/libfritter/blob/master/libfritter/mailer.py
import argparse
import getpass
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr
HOST = 'smtp.gmail.com'
def main(args: argparse.Namespace) -> None:
msg = MIMEMultipart()
msg.attach(MIMEText(args.body_file.read()))
for attachment in args.attachments:
msg.attach(MIMEApplication(attachment.read(), Name=attachment.name))
# Sanity check
parseaddr(args.sender)
parseaddr(args.recipient)
msg['Subject'] = args.subject
msg['From'] = args.sender
msg['To'] = args.recipient
_, user = parseaddr(args.sender)
password = args.password or getpass.getpass(
prompt=f"Password for {user} at {HOST}: ",
)
# Send the message via our own SMTP server.
with smtplib.SMTP_SSL(HOST) as s:
s.login(user, password)
s.send_message(msg)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--password', required=False)
parser.add_argument('sender')
parser.add_argument('recipient')
parser.add_argument('subject')
parser.add_argument('body_file', type=argparse.FileType(mode='r'))
parser.add_argument(
'attachments',
type=argparse.FileType(mode='r'),
nargs=argparse.ZERO_OR_MORE,
)
return parser.parse_args()
if __name__ == '__main__':
main(parse_args())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment