详解Python发送邮件实例

Triagen 2019-04-22

Python发送邮件需要smtplib和email两个模块。也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单。今天,就来好好学习一下使用Python发送邮件吧。

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

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

1.邮件正文是文本的格式

# -*- coding: UTF-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import sys
import csv
import xlrd
from pyExcelerator import *
import os
import xlwt
from xlutils.copy import copy
import pyExcelerator
import datetime
import time

reload(sys)
sys.setdefaultencoding("utf-8")

mailto_list = [""] # 邮件接收方的邮件地址
mail_host = "smtp.exmail.qq.com"  # 邮件传送协议服务器
mail_user = "" # 邮件发送方的邮箱账号
mail_pass = "" # 邮件发送方的邮箱密码

def send_mail(to_list, sub, content):
  me = "天才白痴梦"+"<"+mail_user+">"
  msg = MIMEText(content, _subtype='plain', _charset='utf-8')
  msg['Subject'] = sub  # 邮件主题
  msg['From'] = me
  msg['To'] = ";".join(to_list)
  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

if __name__ == '__main__':
  sub = "天才白痴梦"
  content = '...'
  if send_mail(mailto_list, sub, content):
    print "发送成功"
  else:
    print "发送失败"

2.邮件正文是表格的格式:由于是表格,所以我们选择HTML来实现表格的功能,邮件上面显示的就是HTML实现的内容了。

# -*- coding: UTF-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import sys
import csv
import xlrd
from pyExcelerator import *
import os
import xlwt
from xlutils.copy import copy
import pyExcelerator
import datetime
import time

reload(sys)
sys.setdefaultencoding("utf-8")

mailto_list = [""] # 邮件接收方的邮件地址
mail_host = "smtp.exmail.qq.com"  # 邮件传送协议服务器
mail_user = "" # 邮件发送方的邮箱账号
mail_pass = "" # 邮件发送方的邮箱密码

def send_mail(to_list, sub, content):
  me = "天才白痴梦"+"<"+mail_user+">"
  # 和上面的代码不同的就是,这里我们选择的是html 的格式
  msg = MIMEText(content, _subtype='html', _charset='utf-8')
  msg['Subject'] = sub  # 邮件主题
  msg['From'] = me
  msg['To'] = ";".join(to_list)
  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

if __name__ == '__main__':
  sub = "天才白痴梦"
  html = '<html></html>'
  if send_mail(mailto_list, sub, html):
    print "发送成功"
  else:
    print "发送失败"

3.邮件正文是图片的格式:要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。

def send_mail(to_list, sub, content):
  me = "天才白痴梦"+"<"+mail_user+">"

  msg = MIMEMultipart()
  msg['Subject'] = sub  # 邮件主题
  msg['From'] = me
  msg['To'] = ";".join(to_list)

  txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8')
  msg.attach(txt)

  # <b>:黑体 <i>:斜体
  msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<img alt="" src="cid:image1" />good!', 'html', 'utf-8')
  msg.attach(msgText)

  file1 = "F:\\1.jpg"
  image = MIMEImage(open(file1, 'rb').read())
  image.add_header('Content-ID', '<image1>')
  msg.attach(image)

  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

if __name__ == '__main__':
  sub = "天才白痴梦"
  html = '<html></html>'
  if send_mail(mailto_list, sub, html):
    print "发送成功"
  else:
    print "发送失败"

4.发送邮件附件:邮件附件是图片

def send_mail(to_list, sub, content):
  me = "天才白痴梦"+"<"+mail_user+">"

  msg = MIMEMultipart()
  msg['Subject'] = sub  # 邮件主题
  msg['From'] = me
  msg['To'] = ";".join(to_list)

  txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8')
  msg.attach(txt)

  # # <b>:黑体 <i>:斜体
  # msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<img alt="" src="cid:image1" />good!', 'html', 'utf-8')
  # msg.attach(msgText)
  #
  # file1 = "F:\\1.jpg"
  # image = MIMEImage(open(file1, 'rb').read())
  # image.add_header('Content-ID', '<image1>')
  # msg.attach(image)

  att = MIMEText(open('F:\\1.jpg', 'rb').read(), 'base64', 'utf-8')
  att["Content-Type"] = 'application/octet-stream'
  att["Content-Disposition"] = 'attachment; filename="1.jpg"'
  msg.attach(att)

  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

5.发送群邮件:同时发送给多人
mailto_list = [""]  # 邮件接收方的邮件地址
上面这一行代码是邮件接收方的邮件地址,如果我们需要给多人发送邮件的话,就只需要把对方的邮件帐号绑在这一个列表里就ok了。

加密SMTP

使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件。

方法:只需要在创建SMTP对象后,立刻调用starttls()方法,就创建了安全连接。

smtp_server = 'smtp.qq.com'
smtp_port = 25  # 默认端口号为25
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# 剩下的代码和前面的一模一样:
server.set_debuglevel(1)   # 打印出和SMTP服务器交互的所有信息

以上就是关于Python发送邮件详细解析,希望对大家的学习有所帮助。

相关推荐