1. 程式人生 > >python傳送郵件模板

python傳送郵件模板

python傳送郵件(不帶附件)模板
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '[email protected]'
receiver = '[email protected]'
subject = '報警'
username = '[email protected]'
password = 'xxxx'
msg = MIMEText(strs, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = 'Tim<
[email protected]
>'
msg['To'] = "[email protected]"
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()



python傳送郵件(帶附件) 模板
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

USER = '
[email protected]
'
PASSWORD = 'XXXXXXXXX'
# 如名字所示: Multipart就是多個部分
msg = MIMEMultipart()
HOST = 'smtp.163.com'
msg['subject'] = 'test email from python'
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
text = MIMEText('我是純文字')
msg.attach(text)
#新增附件1
xlsxpart = MIMEApplication(open('test1.xlsx', 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='test1.xlsx')
msg.attach(xlsxpart)
#新增附件2
xlsxpart2 = MIMEApplication(open('test2.xlsx', 'rb').read())
xlsxpart2.add_header('Content-Disposition', 'attachment', filename='test2.xlsx')
msg.attach(xlsxpart2)
#開始傳送郵件
client = smtplib.SMTP()
client.connect(HOST)
client.login(USER, PASSWORD)
client.sendmail('
[email protected]
', ['[email protected]'], msg.as_string())
client.quit()
print('傳送成功........')