本文實(shí)例為大家分享了python3實(shí)現(xiàn)多張圖片附件郵件發(fā)送的具體代碼,供大家參考,具體內(nèi)容如下
我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、久治ssl等。為上千企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的久治網(wǎng)站制作公司直接上代碼,沒(méi)有注釋?zhuān)?/p>
from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.header import Header class Mail(object): def __init__(self, host, nickname, username, password, postfix): self.host = host self.nickname = nickname self.username = username self.password = password self.postfix = postfix def send_mail(self, to_list, subject, content, cc_list=[], encode='gbk', is_html=True, images=[]): me = str(Header(self.nickname, encode)) + "<" + self.username + "@" + self.postfix + ">" msg = MIMEMultipart() msg['Subject'] = Header(subject, encode) msg['From'] = me msg['To'] = ','.join(to_list) msg['Cc'] = ','.join(cc_list) if is_html: mail_msg = '' for i in range(len(images)): mail_msg += '' % (i+1) msg.attach(MIMEText(content + mail_msg, 'html', 'utf-8')) for i, img_name in enumerate(images): with open(img_name, 'rb') as fp: img_data = fp.read() msg_image = MIMEImage(img_data) msg_image.add_header('Content-ID', '' % (i+1)) msg.attach(msg_image) # 將圖片作為附件 # image = MIMEImage(img_data, _subtype='octet-stream') # image.add_header('Content-Disposition', 'attachment', filename=images[i]) # msg.attach(image) else: msg_content = MIMEText(content, 'plain', encode) msg.attach(msg_content) try: s = smtplib.SMTP() # s.set_debuglevel(1) s.connect(self.host) s.login(self.username, self.password) s.sendmail(me, to_list + cc_list, msg.as_string()) s.quit() s.close() return True except Exception as e: print(e) return False def send_mail(to_list, title, content, cc_list=[], encode='utf-8', is_html=True, images=[]): content = ' %s' % content m = Mail('smtp.163.com', 'TV-APP TEST', 'tvapp_qa', 'ujlnluutpfespgxz', '163.com') m.send_mail(to_list, title, content, cc_list, encode, is_html, images) if __name__ == '__main__': images = [ '1.png', '2.png', '3.png', '4.png', ] import time title = 'new images %s' % time.strftime('%H:%M:%S') content = 'this is attach images %s' % time.time() send_mail(['x@163.com'], title, content, ['xx@163.com', 'xxx@163.com'], 'utf-8', True, images)