Skip to content

Instantly share code, notes, and snippets.

@NiceRath
Created January 29, 2026 17:51
Show Gist options
  • Select an option

  • Save NiceRath/99c7c588f1abf9e55703f056499ea843 to your computer and use it in GitHub Desktop.

Select an option

Save NiceRath/99c7c588f1abf9e55703f056499ea843 to your computer and use it in GitHub Desktop.
Simple Python-Script to send Testmails over TLS (587) with authentication
#!/usr/bin/env python3
import smtplib
import ssl
from email.message import EmailMessage
from pathlib import Path
from os.path import basename
from argparse import ArgumentParser
REQUIRE_FROM_DOMAIN = '@<your-domain>.xy'
def main():
msg = EmailMessage()
msg['Subject'] = args.subject
msg['From'] = getattr(args, 'from')
msg['To'] = args.to
msg.set_content(args.body, subtype='html')
if args.attachment is not None:
with open(args.attachment, 'rb') as f:
file_data = f.read()
msg.add_attachment(
file_data, maintype='text', subtype='plain',
filename=args.attachment_name if args.attachment_name is not None else basename(args.attachment),
)
context = ssl.create_default_context()
try:
with smtplib.SMTP(args.server, 587) as server:
server.ehlo()
server.starttls(context=context)
server.ehlo()
if args.user and args.password:
server.login(args.user, args.password)
server.send_message(msg)
print("Email sent successfully!")
except Exception as e:
print(f"Error: {e}")
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument(
'-f', '--from', required=False,
default='[email protected]', help='From E-Mail Address',
)
parser.add_argument('-x', '--server', required=True, help='Server IP/DNS')
parser.add_argument('-t', '--to', required=True, help='To E-Mail Address')
parser.add_argument('-a', '--attachment', required=False, help='Path to attachment')
parser.add_argument('-an', '--attachment-name', required=False, help='Name of attachment')
parser.add_argument('-b', '--body', required=True, help='E-Mail Body')
parser.add_argument('-s', '--subject', required=True, help='E-Mail Subject')
parser.add_argument('-u', '--user', help='SMTP Username')
parser.add_argument('-p', '--password', help='SMTP Password')
args = parser.parse_args()
if args.attachment is not None and not Path(args.attachment).is_file():
raise FileNotFoundError(f'No such file: {args.attachment}')
if getattr(args, 'from').find(REQUIRE_FROM_DOMAIN) == -1:
raise FileNotFoundError(f'From domain needs to be: {REQUIRE_FROM_DOMAIN}')
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment