python群發郵件並將excel附件新增到正文
阿新 • • 發佈:2018-11-11
本文幾個目的:
1。使用smtp庫群發郵件
2。新增郵件的附件
3。將Excel附件新增到正文中
"""
to_addr表示群發集,使用形如('abc.163.com,add.163.com,[email protected]')
html表示要展示在正文中的網頁或者表格等。
password欄位表示郵箱的驗證碼,在開啟smtp協議時記得,並不是郵箱的密碼。
"""
def send_email(to_addr,html):
from_addr = '[email protected]'
password = '*********'
smtp_server = 'smtp.163.com'
# msg=MIMEText('hello,send by python...','plain','utf-8')
msg = MIMEMultipart('alternative')
msg['From'] = u'M10<[email protected]>'
to_addrs = to_addr.split(',')
msg['To'] = ','.join(to_addrs)
#msg['To'] = to_addr
msg['Subject'] = Header(time.strftime("%Y-%m-%d 自動化日報" , time.localtime()), 'utf-8')
with open(filepath, 'rb') as f:
# 設定附件的MIME和檔名,這裡是png型別:
mime = MIMEBase('1', 'xlsx', filename='1.xlsx')
# 加上必要的頭資訊:
mime.add_header('Content-Disposition', 'attachment', filename='1.xlsx')
mime.add_header('Content-ID', '<0>' )
mime.add_header('X-Attachment-Id', '0')
# 把附件的內容讀進來:
mime.set_payload(f.read())
# 用Base64編碼:
encoders.encode_base64(mime)
# 新增到MIMEMultipart:
msg.attach(mime)
msg.attach(MIMEText(html, 'html', 'utf-8'))
try:
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.starttls()
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
print('傳送成功')
except smtplib.SMTPException:
print('傳送失敗')
"""
filepath是Excel檔案的地址
return的file就是html格式的,可以用於上個函式直接在郵箱附件主頁中展示的。
"""
def excel_to_html(filepath):
xd = pd.ExcelFile(filepath)
df = xd.parse()
with codecs.open('/Users/wangxingfan/Desktop/1.html', 'w', 'utf-8') as html_file:
html_file.write(df.to_html(header=True, index=False))
file = open('/Users/wangxingfan/Desktop/1.html').read()
return file