Email 發送
#!/usr/bin/python # -*- coding: UTF-8 -*- import base64 import smtplib from email.mime.text import MIMEText from email.header import Header from email.utils import formataddrdef crypt(source, key):from itertools import cycleresult=''temp=cycle(key)for ch in source:result=result+chr(ord(ch)^ord(next(temp)))return resultsender = 'xxx@aliyun.com' receivers = ['xxx@dingtalk.com'] # 接收郵件,可設置為你的QQ郵箱或者其他郵箱# 三個參數:第一個為文本內容,第二個 plain 設置文本格式,第三個 utf-8 設置編碼 msg = MIMEText('Python 郵件發送測試...', 'plain', 'utf-8') # msg['From'] = Header("S", 'utf-8') # 發送者 # msg['To'] = Header("測試", 'utf-8') # 接收者 msg['From'] = formataddr(["data_deal", sender]) # 發送者 msg['To'] = formataddr(["recv", receivers[0]]) # 接收者 subject = 'Python SMTP 郵件測試'def sendMail(subject, key):error_msg = Nonetry:msg['Subject'] = Header(subject, 'utf-8')# clint = smtplib.SMTP()# EMAIL_HOST, EMAIL_PORT = "smtpdm.aliyun.com", 465# clint.connect(EMAIL_HOST, EMAIL_PORT)EMAIL_HOST, EMAIL_PORT = "smtp.aliyun.com", 465clint = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT)clint.login(sender, crypt('xxx', key))clint.sendmail(sender, receivers, msg.as_string())clint.quit()print("郵件發送成功")except smtplib.SMTPConnectError as e:error_msg= '郵件發送失敗,連接失敗'except smtplib.SMTPAuthenticationError as e:error_msg = '郵件發送失敗,認證錯誤:'except smtplib.SMTPSenderRefused as e:error_msg = '郵件發送失敗,發件人被拒絕:'except smtplib.SMTPRecipientsRefused as e:error_msg = '郵件發送失敗,收件人被拒絕:'except smtplib.SMTPDataError as e:error_msg = '郵件發送失敗,數據接收拒絕:'except smtplib.SMTPException as e:error_msg = '郵件發送失敗, {}'.format(str(e))except Exception as e:error_msg = '郵件發送異常, {}'.format(str(e))if error_msg != None:print("Error: 無法發送郵件")print(error_msg)# sendMail('ttttt', '123')
?