Skip to content

Instantly share code, notes, and snippets.

@chrisdpa-tvx
Created March 12, 2018 15:04
Show Gist options
  • Save chrisdpa-tvx/59ad62b85125291425c24282b41e8b99 to your computer and use it in GitHub Desktop.
Save chrisdpa-tvx/59ad62b85125291425c24282b41e8b99 to your computer and use it in GitHub Desktop.
Send Mail using docker as a relay
#!/usr/bin/env python3
# Start a mail relay using docker:
#
# docker run -p 25:25 namshi/smtp
#
import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid
import csv
def mail_send(to_address, first, last):
if (not first or len(first) < 2):
first = 'Customer'
print("EmailAddress: {}, FirstName: {}, LastName: {}".format(to_address, first, last))
message = EmailMessage()
message['Subject'] = "Subject"
message['From'] = Address("Customer Enquiries", "customer.enquiries", "example.com")
message['To'] = to_address
message.add_header('Content-Type', 'text/html', charset='utf-8')
tvx_cid = make_msgid()
with open("body.html") as html_body_raw:
html_body = html_body_raw.read()
html_body = html_body.replace('__cid_tvx__', tvx_cid[1:-1]).replace('__first__', first)
print("html_body: {}".format(html_body))
message.set_content(html_body, subtype='html')
with open("tvx.png", 'rb') as img:
message.add_related(img.read(), 'image', 'png', cid=tvx_cid)
with open('{}_{}.msg'.format(first, last), 'wb') as f:
f.write(bytes(message))
with smtplib.SMTP('localhost') as s:
s.send_message(message)
csv_reader = csv.reader(open('list.csv', 'r'))
for record in csv_reader:
mail_send(record[2], record[0], record[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment