In yesterday’s post, I wrote about how I learned how to set up a local SMTP server. I came across a problem that I couldn’t solve, and it started getting late.
What’s kind of stupid about sending emails is the fact that you need to stuff all the important data into one big message. For this to work, you need to format your message in a bizarre way so the receiving mail server can make out who the message is coming from, who it is going to, and what they’re sending. This is where multi-part messages come into play.
A multi-part message is basically a dictionary that lets you split up a big jumbled mess and sort it neatly. This makes it a lot easier to talk to a mail server that’s expecting you to provide neatly sorted data.
Handles HTML no problem. Where the problem lies here is that you can’t set variables within the body content. The TO and FROM and SUBJECT can’t get edited.
message = """From: From Peter Krysik <email@example.com> To: To Person <firstname.lastname@example.org> MIME-Version: 1.0 Content-type: text/html Subject: At Your Service this is the body of the email <p>it even supports HTML</p> """
Now you can set variables in the body content, but you lose the HTML. Fix that by parsing the text as HTML. It’s also become very annoying to write the body content in the script. It should be sourced from a text/html file.
msg = MIMEMultipart() msg['From'] = sender msg['To'] = receiver msg['Subject'] = "SUBJECT OF THE EMAIL" body = '<p><span style="float: left; width: 0.8em; font-size: 600%; font-family: algerian, courier; line-height: 80%;">O</span>ur goal at <b>Webs</b> is to connect businesses to their online customers. How do we do that? Let\'s just say we\'ve got a way with this sort of thing.</p>' msg.attach(MIMEText(body, 'html')) text = msg.as_string()