#coding=utf-8 # smtplib负责发送邮件的动作,连接邮箱服务器、登录、发送 # email负责构造邮件,指的是邮箱页面显示,如发件人,收件人,主题,正文,附件等 import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.header import Header from email.utils import formataddr # 设置smtplib所需的参数 from_addr = '发件人邮箱地址' receivers = ['收件人邮件地址'] qqAuthPassword = '发件人邮箱密码' smtp_server = '服务器地址' smtp_port = 587 attach_filename = 'test.py' attach_imagefile = u'1.png' def mail(): ret = True try: # 构造邮件对象MIMEMultipart对象 message = MIMEMultipart('mixed') message['From'] = from_addr message['To'] = ';'.join(receivers) message['Subject'] = u'subject' msgAlternative = MIMEMultipart('alternative') message.attach(msgAlternative) # 构造html mail_msg = ''' <p>邮件发送测试...</p> ''' ## <p><img src='cid:image1'></p> msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 构造图片链接 fp = open(attach_imagefile, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') message.attach(msgImage) # 构造附件 att1 = MIMEText(open(attach_filename, 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1['Content-Disposition'] = 'attachment;filename=' + attach_filename message.attach(att1) # 配置服务器 if smtp_port == 25: smtp = smtplib.SMTP() smtp.connect(smtp_server,smtp_port) elif smtp_port == 465: smtp = smtplib.SMTP_SSL(smtp_server, smtp_port) elif smtp_port == 587: smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.connect(smtp_server,smtp_port) smtp.ehlo() smtp.starttls() smtp.login(from_addr, qqAuthPassword) smtp.sendmail(from_addr, receivers, message.as_string()) smtp.quit() except Exception as e: print('Error--' + str(e)) ret = False return ret ret = mail() if ret: print(u'邮件发送成功') else: print(u'邮件发送失败' )
标签:message,smtp,发送,attach,import,smtplib,port,邮件 From: https://www.cnblogs.com/xiaojiaocx/p/17026860.html