# -*- coding:utf-8 -*-import smtplibimport sslfrom email.header import Headerfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.utils import formataddrdef send_mail(sender, sender_alias, sender_pwd, recipient_list, subject, body, host="sg-smtp.qcloudmail.com", port=465,is_use_ssl=True):try:message = MIMEMultipart('alternative')message['Subject'] = Header(subject, 'UTF-8')message['From'] = formataddr([sender_alias, sender])message['To'] = ",".join(recipient_list)to_addr_list = recipient_listmime_text = MIMEText(body, _subtype='html', _charset='UTF-8')message.attach(mime_text)if is_use_ssl:context = ssl.create_default_context()context.set_ciphers('DEFAULT')client = smtplib.SMTP_SSL(host, port, context=context)else:client = smtplib.SMTP(host, port)client.login(sender, sender_pwd)client.sendmail(sender, to_addr_list, message.as_string())client.quit()print('Send email success!')except smtplib.SMTPConnectError as e:print('Send email failed,connection error:', e.smtp_code, e.smtp_error)except smtplib.SMTPAuthenticationError as e:print('Send email failed,smtp authentication error:', e.smtp_code, e.smtp_error)except smtplib.SMTPSenderRefused as e:print('Send email failed,sender refused:', e.smtp_code, e.smtp_error)except smtplib.SMTPRecipientsRefused as e:print('Send email failed,recipients refused:', e.recipients)except smtplib.SMTPDataError as e:print('Send email failed,smtp data error:', e.smtp_code, e.smtp_error)except smtplib.SMTPException as e:print('Send email failed,smtp exception:', str(e))except Exception as e:print('Send email failed,other error:', str(e))if __name__ == '__main__':# Sender address created in the consolefrom_email = "xxx@xxxx"# SMTP password set in the consolefrom_email_pwd = "xxx"# Recipient email address listto_email_list = ["xxx@xxx1", "xxx@xxx2"]# Sender email aliasfrom_alias = "Test Alias"# Email subjectsubject_txt = "[Test Subject]"# Email contentbody_content = ("<!DOCTYPE html>\\n<html>\\n<head>\\n<meta charset=\\"utf-8\\">\\n<title>hello world</title>\\n</head>\\n<body>\\n ""<h1>My First Heading</h1>\\n <p>My First Paragraph.</p>\\n</body>\\n</html>")# Use SSL to send emails by default; the port can be 465 or 58is_using_ssl = True# SMTP service address, Hong Kong=smtp.qcloudmail.com, Singapore=sg-smtp.qcloudmail.com, Guangzhou=gz-smtp.qcloudmail.comsmtp_host = "sg-smtp.qcloudmail.com"# SMTP port number, 465 and 587 use SSL encryption, 25 uses TLSsmtp_port = 465# Use port 25 to send emails# is_using_ssl = False# smtp_host = "sg-smtp.qcloudmail.com"# smtp_port = 25send_mail(from_email, from_alias, from_email_pwd, to_email_list, subject_txt, body_content,smtp_host, smtp_port, is_using_ssl)
Feedback