? ? 恩,最近自學(xué)Python.在度娘和簡書的幫助下成功完成Python STMP?在阿里云服務(wù)器自動發(fā)郵件,用于自動定時給指定領(lǐng)導(dǎo)發(fā)送報表,郵件發(fā)送代碼如下:
#encoding=utf8
import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email(to_addr, msg_subject,file_name,cc_addr=None,file_path=None):
? ? """
? ? to_addr: 收件人的郵箱地址, 例如 {‘a(chǎn)bc@qq.com','efg@163.com'}
? ? msg_subject: str, 郵件的標(biāo)題
? ? cc_addr: dict, 抄送人的郵箱昵稱和地址, 例如 {'xiaoming@example.com','efg@163.com'}
? ? file_path: str, 附件文件路徑
? ? """
? ? # 第三方 SMTP 服務(wù)
? ? mail_host = "smtp.qiye.aliyun.com"? # 設(shè)置服務(wù)器
? ? mail_user = "XXXXXXXXX"? # 用戶名
? ? mail_pass = "XXXXXXXXX"? # 口令
? ? sender = 'XXX@chunstore.com'? # 發(fā)件人
? ? receivers = to_addr? # 接收郵件,可設(shè)置為你的QQ郵箱或者其他郵箱
? ? # 郵件內(nèi)容
? ? content = MIMEText('''?
? ? -----------------------------------------------------------------------
? ? 自動報表
? ? -----------------------------------------------------------------------
? ? ? ? ? ? ? ? 主要內(nèi)容請查看附件XLS? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? -----------------------------------------------------------------------
? ? 本郵件由系統(tǒng)自動發(fā)送,請勿回復(fù)。
? ? -----------------------------------------------------------------------
? ? ''')
? ? message = MIMEMultipart()
? ? message.attach(content)
? ? message['From'] = 'baobiao@xxxxx.com'? ? ? # 發(fā)件人
? ? print(to_addr)
? ? message['To'] = to_addr? ? ? ? ? ? ? ? ? ? # 收件人
? ? if cc_addr is not None:
? ? ? ? message['Cc'] = cc_addr? # 抄送人
? ? subject = msg_subject
? ? message['Subject'] = Header(subject, 'utf-8')
? ? xlsx = MIMEApplication(open(file_path, 'rb').read())
? ? xlsx["Content-Type"] = 'application/octet-stream'
? ? xlsx.add_header('Content-Disposition', 'attachment', filename=file_name)
? ? message.attach(xlsx)
? ? try:
? ? ? ? smtpObj = smtplib.SMTP()
? ? ? ? smtpObj = smtplib.SMTP_SSL(mail_host,465)? ? ? # SSL方式發(fā)送 端口號465 因阿里云25端口號封所以改用465
? ? ? ? smtpObj.login(mail_user, mail_pass)? ? ? ? ?
? ? ? ? smtpObj.sendmail(sender, receivers, message.as_string())
? ? ? ? print("郵件發(fā)送成功")
? ? except? Exception as e:
? ? ? ? print(e)
if __name__ == "__main__":
? ? to_addr =?abc@qq.com # 收件人地址
????cc_addr = bcd@qq.com?#?抄送人地址多個地址,號隔開
? ? msg_subject = '我是郵件標(biāo)題'
? ? file_path = "D:\\PySendMailrpot\\2020-05-14商品信息變更.xlsx"
? ? today = datetime.date.today()
????file_name=str(today)+'商品信息變更.xlsx'
? ? send_email(to_addr, msg_subject,file_name,cc_addr=None,file_path=None)