python發送郵件(帶附件)+屏幕截圖
import smtplib
#smtplib這個模塊是管發郵件
from email.mime.text import MIMEText
#構造郵件內容
from email.mime.multipart import MIMEMultipart
#髮帶附件的郵件用的
email_host = 'smtp.163.com' #郵箱服務器地址
email_user = '[email protected]' # 發送者賬號
email_pwd = 'XXX'
# 發送者密碼是郵箱的授權碼,不是登錄的密碼
maillist = '[email protected]'
#收件人郵箱,多個賬號的話,用逗號隔開
new_msg = MIMEMultipart()
#構建了一個能發附件的郵件對象
new_msg.attach(MIMEText('這是Python測試發郵件的郵件,不要回復'))
# 郵件內容
new_msg['Subject'] = 'Python測試郵件帶附件' # 郵件主題
new_msg['From'] = email_user # 發送者賬號
new_msg['To'] = maillist # 接收者賬號列表
att = MIMEText(open('like_report.txt').read())
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="haha.txt"'
new_msg.attach(att)
smtp = smtplib.SMTP(email_host,port=25) # 連接郵箱,傳入郵箱地址,和端口號,smtp的端口號是25
smtp.login(email_user, email_pwd) # 發送者的郵箱賬號,密碼
smtp.sendmail(email_user, maillist, new_msg.as_string())
# 參數分別是發送者,接收者,第三個是把上面的發送郵件的內容變成字符串
smtp.quit() # 發送完畢後退出smtp
已調試通過,以下是完整代碼
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from datetime import datetime import time from PIL import ImageGrab from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import os mailto_list=['[email protected]'] #收件人(列表) huawei_to_list= ['[email protected]'] mail_host="smtp.163.com" #使用的郵箱的smtp服務器地址,這裏是163的smtp地址 mail_user="[email protected]" #用戶名 mail_pass="" #密碼 mail_postfix="163.com" #郵箱的後綴,網易就是163.com def send_mail(to_list,sub,content,pic_name): me="hello"+"<"+mail_user+"@"+mail_postfix+">" #msg = MIMEText(content,_subtype='plain') msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) #將收件人列表以‘;’分隔 puretext = MIMEText('content: '+content) msg.attach(puretext) jpgpart = MIMEApplication(open(pic_name, 'rb').read()) jpgpart.add_header('Content-Disposition', 'attachment', filename=pic_name) msg.attach(jpgpart) try: server = smtplib.SMTP() server.connect(mail_host) #連接服務器 server.login(mail_user,mail_pass) #登錄操作 server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False while True: try: time_now = str(datetime.now()) pic = ImageGrab.grab() pic_name = time.strftime('%Y-%m-%d-%H-%M-%S')+'.jpg' pic.save(pic_name) my_info = 'test_time_for_me' send_mail(huawei_to_list,time_now,my_info,pic_name) send_mail(mailto_list,time_now,my_info,pic_name) #os.remove(pic_name) print time_now time.sleep(600) except Exception ,e: print e send_mail_bak() time.sleep(300)