python3 邮件发送

时间:2021-09-15 18:04:52

这是搜罗网络上的文章总结的一份文档,

参考:

  https://www.jb51.net/article/140604.htm

  https://www.jb51.net/article/140604.htm

一、发送不带附件的邮件

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import smtplib
from email.header import Header
from email.mime.text import MIMEText # 设置邮件头部显示
message = MIMEText("邮件测试", 'plain', 'utf-8') # 邮件发送正文(随意定义)
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8') # 邮件显示主题(随意定义)
message['From'] = '孔扎根' # 邮件显示发件人(随意定义)
message['To'] = '天心明月' # 邮件显示收件人(随意定义) # 配置服务器及账号信息
sender = 'xx@xxx.cn' # 发件人
receivers = ['xxxx@qq.com'] # 收件人
mail_host = 'smtp.xxxx.cn' # 发送邮件smtp服务器
mail_user = 'xxxx@xxxx.cn' # 登陆邮箱账号
mail_pass = 'xxxxxzzz!' # 登陆邮箱密码 try:
smtpObj = smtplib.SMTP() # 构造smtp实例
smtpObj.connect(mail_host, 25) # 连接smtp服务器
smtpObj.login(mail_user, mail_pass) # 登陆邮箱
smtpObj.sendmail(sender, receivers, message.as_string()) # 发送邮件正文
print("OK")
except:
print("err")

 

二、发送带附件的邮件

  当不设置文件内容时,可以发送普通邮件。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart # 构建MIMEMultipart对象,并在其中添加邮件内容信息
message = MIMEMultipart()
content = MIMEText("邮件测试222222", 'plain', 'utf-8') # 封装邮件内容
message.attach(content) # 添加到实例
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8') # 主题(随意定义)
message['From'] = '孔扎根' # 发件人(随意定义)
message['To'] = '天心明月' # 收件人(随意定义) attr = MIMEText(open('./201812.csv', 'rb').read(),'base64', 'utf-8') # 封装邮件内容
attr['Content-Type'] = 'application/octet-stream'
attr['Content-Disposition'] = 'attachment; filename =' + '201812.csv'
message.attach(attr) # 添加到实例(文件形式) # 配置服务器及账号信息
sender = 'xxxx@xxxx.cn' # 发件人
receivers = ['xxxxxx@qq.com'] # 收件人
mail_host = 'smtp.xxxx.cn' # 发送邮件smtp服务器
mail_user = 'xxxx@xxxx.cn' # 登陆邮箱账号
mail_pass = 'zzzzz' # 登陆邮箱密码 try:
smtpObj = smtplib.SMTP() # 构造smtp实例
smtpObj.connect(mail_host, 25) # 连接smtp服务器
smtpObj.login(mail_user, mail_pass) # 登陆邮箱
smtpObj.sendmail(sender, receivers, message.as_string()) # 发送邮件正文
print("OK")
except:
print("err")

  

三、模板类

  有些函数没有写出,只是个简单例子

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
发送邮件:
1、fm=None 发送普通邮件
2、fm 非空 发送带附件的邮件
"""
import smtplib
import datetime
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart from lion import Base
from logCl import log
logger = log("邮箱登陆") class SendMyEmail(Base):
def __init__(self):
Base.__init__(self)
self.sec = self.SectionEmail() def loginEmail(self):
# 登陆邮箱
try:
smtpObj = smtplib.SMTP() # 创建实例
smtpObj.connect(self.sec['host'], 25) # 连接smtp
smtpObj.login(self.sec['user'],
self.sec['password']) # 通过smtp登陆邮箱
logger.info("Login Succ %s" % datetime.datetime.now())
return smtpObj
except:
logger.error("Login Err %s" % datetime.datetime.now())
return "err" def sendMsg(self, Subject, From, To, msg, fm=None):
"""
:param Subject: 邮件主题
:param From: 显示发件人名称
:param To: 显示收件人名称
:param msg: 发送正文内容
:param fm: 发送的附件
"""
# 发送邮件
ret = self.loginEmail()
if ret != 'err':
try:
# 设置邮件头部
message = MIMEMultipart() # 可在此对象中添加 邮件内容和附件内容
message.attach(MIMEText(msg, 'plain', 'utf-8')) # 添加邮件内容
message['Subject'] = Header(Subject, 'utf-8') # 设置邮件主题
message['From'] = From # 设置发件人名称
message['To'] = To # 设置收件人名称
# 构造附件
if fm:
attr = MIMEText(open(fm, 'rb').read(), 'base64', 'utf-8') # 包装附件内容
attr['Content-Type'] = 'application/octet-stream' # 设置Content-Type属性
attr['Content-Disposition'] = 'attachment; filename =' + fm # 设置附件名称
message.attach(attr) # 添加邮件内容(文件)
# 发送邮件
ret.sendmail(self.sec['sender'],
self.sec['receiver'].split(","),
message.as_string())
logger.info("Send Msg OK %s" % datetime.datetime.now())
except:
logger.info("Send Msg Err %s" % datetime.datetime.now())
else:
raise Exception("Error user or password, Pleas Check config!!")