python3 电子邮件

python3 电子邮件
python教程推荐 廖雪峰 - python3教程

不带附件的邮件

from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.utils import parseaddr,formataddr
import smtplib

def msg_format(s):
    name,addr=parseaddr(s)
    return formataddr((Header(name,'utf-8').encode('utf-8'),addr))

user=input('Please enter your email: ')
passwd=input('Please enter the password: ')
smtp_server=input('Please enter your SMTP_Server address: ')
to=input('Send the mail to: ')
mail_title=input('mail title: ')
#mail_body=input('mail body: ')

#msg=MIMEText(mail_body,'plain','utf-8')
msg=MIMEText('<html><body><h1>哈哈</h1><h1>哈哈</h1><h1>哈哈</h1><h1>哈哈</h1></body></html>','html','utf-8')
msg['From']=msg_format(user)
msg['To']=msg_format(to)
msg['Subject']=Header(mail_title,'utf-8').encode('utf-8')

server=smtplib.SMTP_SSL(smtp_server,465) # SSL表示加密的连接。不加SSL则默认25端口
server.set_debuglevel(1)
server.login(user,passwd)
server.sendmail(user,[to],msg.as_string())
server.quit()

带附件(图片)

from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.utils import parseaddr,formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import smtplib

def msg_format(s):
    name,addr=parseaddr(s)
    return formataddr((Header(name,'utf-8').encode('utf-8'),addr))

user=input('Please enter your email: ')
passwd=input('Please enter the password: ')
smtp_server=input('Please enter your SMTP_Server address: ')
to=input('Send the mail to: ')
mail_title=input('mail title: ')
#mail_body=input('mail body: ')

#msg=MIMEText(mail_body,'plain','utf-8')
#msg=MIMEMultipart() # 只显示html版本
msg=MIMEMultipart('alternative') # 兼容不能渲染html的邮件客户端
msg.attach(MIMEText('<html><body><h1>哈哈</h1><h1>哈哈</h1><h1>哈哈</h1><h1>哈哈</h1><p><img src ="cid:0"></p></body></html>','html','utf-8')) # cid:0表示将图片附件放在正文
with open('./ipt.png','rb') as f:
    mime=MIMEBase('image','png',filename='ipt.png') # 创建附件 类型为image png格式。附件名为ipt.png
    mime.add_header('Content-Disposition', 'attachment', filename='ipt.png')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    mime.set_payload(f.read()) # 读取本地附件
    encoders.encode_base64(mime) # base64编码
    msg.attach(mime) # 加入邮件中
msg['From']=msg_format(user)
msg['To']=msg_format(to)
msg['Subject']=Header(mail_title,'utf-8').encode('utf-8')

server=smtplib.SMTP_SSL(smtp_server,465)
server.set_debuglevel(1)
server.login(user,passwd)
server.sendmail(user,[to],msg.as_string())
server.quit()

邮件内容结构

Message
+- MIMEBase
   +- MIMEMultipart
   +- MIMENonMultipart
      +- MIMEMessage
      +- MIMEText
      +- MIMEImage