Created
January 13, 2024 08:21
-
-
Save h4sh5/2d64d163e71ff9fed7d91d5922fc2004 to your computer and use it in GitHub Desktop.
send email (text and html) using python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
import dns.resolver | |
msg = MIMEMultipart('alternative') | |
plain_part = MIMEText('testing plaintext 123', 'plain') | |
html_part = MIMEText('<h1>Test</h1><p>this is a test email</p>', 'html') | |
msg.attach(html_part) | |
msg.attach(plain_part) | |
if len(sys.argv) < 3: | |
print("Usage: <server|auto> <sender> <recipient> [recipient 2] [recipient 3] .. ") | |
exit(1) | |
server = sys.argv[1] | |
# me == the sender's email address | |
# you == the recipient's email address | |
msg['Subject'] = 'Test email' | |
sender = sys.argv[2] | |
msg['From'] = sys.argv[2] | |
recipients = sys.argv[3:] | |
msg['To'] = ','.join(recipients) | |
if server == 'auto': | |
# use the first recipient to figure out mail server | |
domain = recipients[0].split('@')[1] | |
for x in dns.resolver.resolve(domain, 'MX'): | |
server = x.to_text().split('\n')[0].split(' ')[1] # get first domain | |
print("sending using server:", server) | |
# exit() | |
# Send the message via our own SMTP server, but don't include the | |
# envelope header. | |
s = smtplib.SMTP(server) | |
response = s.sendmail(sender, recipients, msg.as_string()) | |
print("response:", response) | |
s.quit() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment