Using python to send email through TLS
<p>I am trying to automate sending email through a python script. I am presently using an expect script to use openssl s_client to connect to the server. Presently we only use a certificate file along with the username password and it allows me to send the email. I found another question in which it was mentioned that in python you either need a hack to or a wrapper around the smtp class to use only the CA cert file and not the key file(which i don't have). </p>

<pre><code>&gt;&gt;&gt; smtpobj = smtplib.SMTP("mymailserver.com",465)
Traceback (innermost last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "C:\Program Files (x86)\Python35-32\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
  File "C:\Program Files (x86)\Python35-32\lib\smtplib.py", line 337, in connect
(code, msg) = self.getreply()
  File "C:\Program Files (x86)\Python35-32\lib\smtplib.py", line 390, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host
</code></pre>

<p>The problem I am facing right now is that I am unable to connect to the server through python.</p>

<p>If I use the certificate file to connect through </p>

<pre><code>smtplib.SMTP_SSL(myserver, port, certfile="mycert.cert") 
</code></pre>

<p>then it throws the following error.</p>

<pre><code>ssl.SSLError: [Errno 336265225] _ssl.c:339: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib
</code></pre>

<p>Please note, I am able to connect to the server using thunderbird, without a cert file. Any ideas, on how I can use python smtp(tls) to send the emails? </p>

<p>You need to remove the key pass phrase first using -</p>

<pre><code>openssl rsa -in key.pem -out tempkey.pem
</code></pre>

<p>And then type passphrase once more - </p>

<pre><code>openssl rsa -in mycert.pem -out tempkey.pem
openssl x509 -in mycert.pem &gt;&gt;tempkey.pem
</code></pre>

<p>Refer <a href="https://www.madboa.com/geek/openssl/#key-removepass" rel="nofollow">this</a> for more info.</p>

python email ssl