This example use provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. This example python code uses the OpenSSL library for solved the issue SSL bad handshake in Alibaba cloud.
Python
import email
import logging
import os
import json
import smtplib
from argparse import ArgumentParser
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import ssl
class SMTPMailer(object):
"""SMTPMailer is an simple SMTP email sender."""
def __init__(self,
username,
password,
sender = 'example@mail.imc',
recipients=[],
cc=[],
attachments=[],
subject='',
body='',
mime_subtype='html',
host='smtp.alibaba-inc.com',
port=465):
self.__log = logging.getLogger('app.sub')
self.host = host
self.port = port
self.username = username
self.password = password
self.sender = sender
self.__recipients = recipients
self.__cc = cc
self.__subject = subject
self.__body = body
self.__attachments = attachments
self.__mime_subtype = mime_subtype
@classmethod
def build_from_json(cls, rawjs):
"""
Build an SMTPMailer from a JSON string.
Args:
rawjs: the JSON string, e.g.
{
"smtp": {
"host": "smtp.alibaba-inc.com",
"port": 465,
"username": "mingjie.tmj@alibaba-inc.com",
"password": "******"
},
"from": "mingjie.tmj@alibaba-inc.com",
"to": [ "mingjie.tmj@alibaba-inc.com" ],
"cc": [],
"subject": "This is really wonderful",
"body": "Body Game",
"attachments": [ "./smtp_mailer.py" ]
}
"""
o = cls('', '')
js = json.loads(rawjs)
o.host = js['smtp'].get('host', 'smtp.alibaba-inc.com')
o.port = js['smtp'].get('port', 465)
o.username = js['smtp']['username']
o.password = js['smtp']['password']
o.sender = js['from']
o.recipients = js['to']
o.cc = js['cc']
o.subject = js['subject']
o.body = js['body']
o.attachments = js['attachments']
return o
def send(self):
"""Send mail to recipients."""
outer = MIMEMultipart()
outer.set_charset('utf-8')
outer['From'] = self.sender
outer['To'] = ', '.join(self.__recipients)
outer['CC'] = ', '.join(self.__cc)
outer['Subject'] = Header(self.__subject, 'utf-8')
outer['Message-id'] = email.utils.make_msgid()
outer['Date'] = email.utils.formatdate()
status=True
# attach plain text body
text_body = MIMEText(self.__body, self.__mime_subtype, _charset='utf-8')
outer.attach(text_body)
# attach the files
for filename in self.__attachments:
if not os.path.isfile(filename):
raise Exception('attachment "%s" is not a file' % (filename))
base_filename = os.path.basename(filename)
fp = open(filename, 'rb')
attachment = MIMEApplication(fp.read(), Name=base_filename)
fp.close()
attachment.add_header(
'Content-Disposition', 'attachment', filename=base_filename)
outer.attach(attachment)
context=ssl.create_default_context()
context.set_ciphers("DEFAULT")
s = smtplib.SMTP_SSL(host=self.host, port=self.port,context=context)#
s.ehlo()
s.set_debuglevel (0)
#s.starttls ()
try:
s.login(self.username, self.password)
except smtplib.SMTPAuthenticationError as serr:
self.get_Log().error(serr.strerror)
raise Exception("SMTP Autentication Error " + serr.strerror)
s.ehlo()
try:
self.get_Log().info(self.sender + " " + ''.join(self.__recipients) + " " + outer.as_string())
s.sendmail(self.sender, self.__recipients, outer.as_string())
except smtplib.SMTPException as serr:
self.get_Log().error(serr.strerror)
raise Exception("SMTP Send Error " + serr.strerror)
s.ehlo()
s.quit()
def to_json(self):
"""Get JSON representation string of this SMTPMailer object."""
return json.dumps(self.__dict__, indent=4)
def get_Log(self):
return self.__log