<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>tls &#8211; Luxing Huang</title>
	<atom:link href="https://luxing.im/tag/tls/feed/" rel="self" type="application/rss+xml" />
	<link>https://luxing.im</link>
	<description>Thoughs and things</description>
	<lastBuildDate>Tue, 31 May 2016 13:26:56 +0000</lastBuildDate>
	<language>en-CA</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
<site xmlns="com-wordpress:feed-additions:1">58771605</site>	<item>
		<title>Sending email with Python</title>
		<link>https://luxing.im/sending-email-with-python/</link>
					<comments>https://luxing.im/sending-email-with-python/#respond</comments>
		
		<dc:creator><![CDATA[Luxing Huang]]></dc:creator>
		<pubDate>Tue, 22 Mar 2016 19:41:37 +0000</pubDate>
				<category><![CDATA[Techie Stuff]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[smtplib]]></category>
		<category><![CDATA[tls]]></category>
		<guid isPermaLink="false">https://luxing.im/?p=629</guid>

					<description><![CDATA[This is a note from learning Python&#8217;s email and smtplib modules. Most of emails nowadays consists of 3 parts: plain text content, HTML content and attachments. Python&#8217;s smtplib library indeed saved us a lot of work. 1. Create a multipart/alternative email envelope. from email.mime.multipart import MIMEMultipart alter = MIMEMultipart('alternative') msg = MIMEMultipart() This will create &#8230; <p class="link-more"><a href="https://luxing.im/sending-email-with-python/" class="more-link">Continue reading<span class="screen-reader-text"> "Sending email with Python"</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>This is a note from learning Python&#8217;s <code>email</code> and <code>smtplib</code> modules.<br />
Most of emails nowadays consists of 3 parts: plain text content, HTML content and attachments. Python&#8217;s <code>smtplib</code> library indeed saved us a lot of work.<br />
<span id="more-629"></span></p>
<p>1. Create a multipart/alternative email envelope.</p>
<pre>
from email.mime.multipart import MIMEMultipart
alter = MIMEMultipart('alternative')
msg = MIMEMultipart()
</pre>
<p>This will create an envelope that will contain all 3 mentioned parts. In mutt&#8217;s view:</p>
<pre>
1 <no description>                    [multipa/alternativ, 7bit, 16K] 
2 ├─><no description>                 [text/plain, base64, utf-8, 0.1K] 
3 ├─><no description>                 [text/html, base64, utf-8, 0.1K]  
4 ca.crt                              [applica/octet-stre, base64, 1.5K]
</pre>
<p>Some MIME type is truncated, but you get the idea.</p>
<p>2. Unicode<br />
You will have to append the coding part in the source file.</p>
<pre>
#!/usr/bin/python
# -*- coding: utf-8 -*-
</pre>
<p>The second line must exist.</p>
<p>Then a unicode title and text:</p>
<pre>
from email.mime.text import MIMEText

# msg and alter is derived from the previous example
msg['Subject'] = u'中文'
text = u'正在用Python写东西'
alter.attach(MIMEText(text, 'plain', 'utf-8'))

msg.attach(alter)
</pre>
<p>Appending HTML just change the <code>plain</code> to <code>html</code> when you call <code>MIMEText</code> against HTML content.</p>
<p>3. Add attachments<br />
Mind the relative / absolute path from the location you execute the script. It&#8217;s recommend to use absolute path.</p>
<pre>
from os.path import basename, dirname, realpath

# assuming I will attach all the files in the same location as the script itself, also a file from other relative path.
cwd = dirname(realpath(__file__))
files = ['myfile.bin', 'herfile.bin', '../other/dir/s.bin']

for f in files:
        # use absolute path
        with open(cwd + '/' + f, "rb") as fil:
            msg.attach(MIMEApplication(
                fil.read(),
                Content_Disposition='attachment; filename="%s"' % basename(f),
                Name=basename(f)
            ))
</pre>
<p>4. Message ID.<br />
Some SMTP server supports adding message id to your email on a specific port, e.g. 25. But when you use <code>starttls</code> to connect the SMTP or use a different port, e.g. 587, Message-Id may not be added automatically. So your email probably won&#8217;t be received as it&#8217;s required in <a href="https://tools.ietf.org/html/rfc2822.html" target="_blank">RFC 2822</a>.</p>
<p>One way to get around that is to generate your own message id. Then you could use <code>starttls()</code> to send your emails securely.</p>
<pre>
from email.utils import make_msgid

# Inherit the msg from above example.
msg['Message-Id'] = make_msgid('example.com')

smtp = smtplib.SMTP('smtp.example.com', 587)
smtp.starttls()
smtp.login('sender@example.com', 'emailpassword')
smtp.sendmail(sender, to, msg.as_string().encode('utf-8'))
smtp.quit()
</pre>
<p>Note that the message id it generated will use the host name of your current machine if you do not specify.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://luxing.im/sending-email-with-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">629</post-id>	</item>
	</channel>
</rss>
