Python - 发送邮件,发送邮件Python,0. 邮件知识介绍E


0. 邮件知识介绍

E-mail服务器流程

  技术分享图片

E-mail格式

Content-Type: text/plain; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitTo: [email protected]From: [email protected]163.comSubject: This is a test emailDate: Wed, 22 Apr 2015 22:26:32 +0800Message-ID: <[email protected]>  Hello,   this is an autotest email.---anonimous

base64编码

  SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本、HTML、带附件的邮件

  发送邮件用到Python的两个模块 email 和 smtplib,其中email用于构造邮件,而smtplib负责发送邮件

  下面我们分别介绍Python通过第三方SMTP服务器分别发送纯文本、HTML、带附件的邮件

1. 发送纯文本邮件

  Header对象用于对邮件中的字符串进行编码

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptiondef send_mail():    # 第三方SMTP邮件服务器信息    # SMTP发件服务器地址    mail_host = ‘smtp.exmail.qq.com‘    # 登录SMT服务器的用户名    mail_user = ‘[email protected]‘    # 登录SMTP服务器的密码,对于126、163邮箱,此处是授权密码而不是登录密码    mail_pass = ‘xxxx‘    # 发送人    sender = ‘[email protected]‘    # 接收邮件地址,可以填写多个地址    receivers = [‘[email protected]‘, ‘[email protected]‘]    # 邮件正文    content = ‘Hello World!‘      # 通过MIMETEXT对象构造邮件,参数分别为邮件内容,邮件MIMETYPE,字符集    msg = MIMEText(content, ‘plain‘, ‘utf-8‘)    # 邮件标题栏显示的发件人    msg[‘From‘] = Header(sender, ‘utf-8‘)    # 邮件标题栏处显示的收件人    msg[‘To‘] = Header(‘,‘.join(receivers), ‘utf-8‘)    # 邮件标题    msg[‘Subject‘] = Header(‘Python Test‘, ‘utf-8‘)    # 发送邮件    try:        # 通过SMTP对象负责发送邮件,参数分别为SMTP服务器地址,SMTP服务器监听的端口号,        # 此处可以使用非加密(SMTP)或加密(SMTP_SSL)方式进行传输, 非加密默认监听端口号为25,加密为465        # smtp_obj = SMTP(mail_host, 25)        smtp_obj = SMTP_SSL(mail_host, 465)        # 登录        smtp_obj.login(mail_user, mail_pass)        # 发送邮件        smtp_obj.sendmail(sender, receivers, msg.as_string())        print(‘Send mail successful‘)    except SMTPException:        print(‘Email failed to send‘)if __name__ == ‘__main__‘: send_mail()

  网易邮箱通过下图所示的设置,授权第三方应用程序通过其发送邮件

  技术分享图片

  技术分享图片

2. 发送HTML邮件

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptiondef send_mail():    mail_host = ‘smtp.exmail.qq.com‘    mail_user = ‘[email protected]‘    mail_pass = ‘224517Ok‘    sender = ‘[email protected]‘    receivers = [‘[email protected]‘, ‘[email protected]‘]    content = """    <html>        <p>Welcome to my site</p>        <a href=‘https://www.cnblogs.com/zhubiao/‘>https://www.cnblogs.com/zhubiao</a>        </html>    """       # 将MIME类型修改为html即可    msg = MIMEText(content, ‘html‘, ‘utf-8‘)    msg[‘From‘] = Header(sender, ‘utf-8‘)    msg[‘To‘] = Header(‘,‘.join(receivers), ‘utf-8‘)    msg[‘Subject‘] = Header(‘Python Test‘, ‘utf-8‘)    # 发送邮件    try:        # smtp_obj = SMTP(mail_host, 25)        smtp_obj = SMTP_SSL(mail_host, 465)        smtp_obj.login(mail_user, mail_pass)        smtp_obj.sendmail(sender, ‘,‘.join(receivers), msg.as_string())        print(‘Email sent successfully‘)    except SMTPException:        print(‘Email failed to send‘)if __name__ == ‘__main__‘:    send_mail()    

3. 发送带附件的邮件

from email.header import Headerfrom email.mime.text import MIMETextfrom smtplib import SMTP, SMTP_SSL, SMTPExceptionfrom email.mime.multipart import MIMEMultipartdef send_mail():    # 第三方SMTP服务器连接信息    mail_host = ‘smtp.exmail.qq.com‘    mail_user = ‘[email protected]‘    mail_pass = ‘224517Ok‘    sender = ‘[email protected]‘    receivers = [‘[email protected]‘, ‘[email protected]‘]    # 创建MIMEMultipart对象,可包含text、image、html等混合类型    msg = MIMEMultipart()    # 邮件首部    msg[‘From‘] = Header(sender, ‘utf-8‘)    msg[‘To‘] = Header(‘,‘.join(receivers), ‘utf-8‘)    msg[‘Subject‘] = Header(‘Python Mail Test‘, ‘utf-8‘)    # 邮件正文内容    # 邮件正文为html, 插入一张图片,图片来自于附件,其中cid:0表示附件首部键值对Content-ID : <0>, Content-ID值自定义。    content = """    <img src=‘cid:0‘/>    """    msg_content = MIMEText(content, ‘html‘, ‘utf-8‘)    msg.attach(msg_content)    # 附件1    att1 = MIMEText(open(‘test.xlsx‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘)    att1[‘Content-Type‘] = ‘application/octet-stream‘    att1[‘Content-Disposition‘] = ‘attachment; filename= "test.xlsx"‘    msg.attach(att1)    # 附件2    att2 = MIMEText(open(‘test.jpg‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘)    att2[‘Content-Type‘] = ‘application/octet-stream‘    att2[‘Content-Disposition‘] = ‘attachment; filename= "test.jpg"‘    att2[‘Content-ID‘] = ‘<0>‘    msg.attach(att2)    # 发送邮件    try:        # smtp_obj = SMTP(mail_host, 25)        smtp_obj = SMTP_SSL(mail_host, 465)        smtp_obj.login(mail_user, mail_pass)        smtp_obj.sendmail(sender, ‘,‘.join(receivers), msg.as_string())        print(‘Email sent successfully‘)    except SMTPException:        print(‘Email failed to send‘)if __name__ == ‘__main__‘:    send_mail()

Python - 发送邮件

评论关闭