Python smtplib实现发送邮件功能
作者:Johnny 发布时间:2021-02-14 20:07:26
标签:Python,smtplib
本文实例为大家分享了Python smtplib发送邮件功能的具体代码,供大家参考,具体内容如下
解决之前版本的问题,下面为最新版
#!/usr/bin/env python
# coding:gbk
"""
FuncName: sendemail.py
Desc: sendemail with text,image,audio,application...
Date: 2016-06-20 10:30
Home: http://blog.csdn.net/z_johnny
Author: johnny
"""
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import COMMASPACE
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
import ConfigParser
import smtplib
import os
class MyEmail:
def __init__(self, email_config_path, email_attachment_path):
"""
init config
"""
config = ConfigParser.ConfigParser()
config.read(email_config_path)
self.attachment_path = email_attachment_path
self.smtp = smtplib.SMTP()
self.login_username = config.get('SMTP', 'login_username')
self.login_password = config.get('SMTP', 'login_password')
self.sender = config.get('SMTP', 'login_username') # same as login_username
self.receiver = config.get('SMTP', 'receiver')
self.host = config.get('SMTP', 'host')
#self.port = config.get('SMTP', 'port') 发现加入端口后有时候发邮件出现延迟,故暂时取消
def connect(self):
"""
connect server
"""
#self.smtp.connect(self.host, self.port)
self.smtp.connect(self.host)
def login(self):
"""
login email
"""
try:
self.smtp.login(self.login_username, self.login_password)
except:
raise AttributeError('Can not login smtp!!!')
def send(self, email_title, email_content):
"""
send email
"""
msg = MIMEMultipart() # create MIMEMultipart
msg['From'] = self.sender # sender
receiver = self.receiver.split(",") # split receiver to send more user
msg['To'] = COMMASPACE.join(receiver)
msg['Subject'] = email_title # email Subject
content = MIMEText(email_content, _charset='gbk') # add email content ,coding is gbk, becasue chinese exist
msg.attach(content)
for attachment_name in os.listdir(self.attachment_path):
attachment_file = os.path.join(self.attachment_path,attachment_name)
with open(attachment_file, 'rb') as attachment:
if 'application' == 'text':
attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
elif 'application' == 'image':
attachment = MIMEImage(attachment.read(), _subtype='octet-stream')
elif 'application' == 'audio':
attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
else:
attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')
attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))
# make sure "attachment_name is chinese" right
msg.attach(attachment)
self.smtp.sendmail(self.sender, receiver, msg.as_string()) # format msg.as_string()
def quit(self):
self.smtp.quit()
def send():
import time
ISOTIMEFORMAT='_%Y-%m-%d_%A'
current_time =str(time.strftime(ISOTIMEFORMAT))
email_config_path = './config/emailConfig.ini' # config path
email_attachment_path = './result' # attachment path
email_tiltle = 'johnny test'+'%s'%current_time # as johnny test_2016-06-20_Monday ,it can choose only file when add time
email_content = 'python发送邮件测试,包含附件'
myemail = MyEmail(email_config_path,email_attachment_path)
myemail.connect()
myemail.login()
myemail.send(email_tiltle, email_content)
myemail.quit()
if __name__ == "__main__":
# from sendemail import SendEmail
send()
配置文件emailConfig.ini
路径要与程序对应
;login_username : 登陆发件人用户名
;login_password : 登陆发件人密码
;host:port : 发件人邮箱对应的host和端口,如:smtp.163.com:25 和 smtp.qq.com:465
;receiver : 收件人,支持多方发送,格式(注意英文逗号): 123456789@163.com,zxcvbnm@qq.com
[SMTP]
login_username = johnny@163.com
login_password = johnny
host = smtp.163.com
port = 25
receiver = johnny1@qq.com,johnny2@163.com,johnny3@gmail.com
之前版本出现的问题:
#!/usr/bin/env python
#coding: utf-8
'''''
FuncName: smtplib_email.py
Desc: 使用smtplib发送邮件
Date: 2016-04-11 14:00
Author: johnny
'''
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import COMMASPACE,formatdate
from email import encoders
def send_email_text(sender,receiver,host,subject,text,filename):
assert type(receiver) == list
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join(receiver)
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text)) #邮件正文内容
for file in filename: #邮件附件
att = MIMEBase('application', 'octet-stream')
att.set_payload(open(file, 'rb').read())
encoders.encode_base64(att)
if file.endswith('.html'): # 若不加限定,jpg、html等格式附件是bin格式的
att.add_header('Content-Disposition', 'attachment; filename="今日测试结果.html"') # 强制命名,名称未成功格式化,如果可以解决请联系我
elif file.endswith('.jpg') or file.endswith('.png') :
att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"')
else:
att.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
msg.attach(att)
smtp = smtplib.SMTP(host)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(username,password)
smtp.sendmail(sender,receiver, msg.as_string())
smtp.close()
if __name__=="__main__":
sender = 'qqq@163.com'
receiver = ['www@qq.com']
subject = "测试"
text = "johnny'lab test"
filename = [u'测试报告.html','123.txt',u'获取的信息.jpg']
host = 'smtp.163.com'
username = 'qqq@163.com'
password = 'qqq'
send_email_text(sender,receiver,host,subject,text,filename)
已测试通过,使用Header并没有变成“头”,故未使用
若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢(已解决,见上面最新版)
点击查看:Python 邮件smtplib发送示例
来源:https://blog.csdn.net/z_johnny/article/details/51146300


猜你喜欢
- 项目结构:源代码:# -*- coding: utf-8 -*-"""@date: 2022/01
- 1.HTTP请求格式: <request line> <headers> <blank line> [&
- 今天彬Go要向大家推荐9款很棒的可在网页中绘制图表的JavaScript脚本,这些有趣的JS脚本可以帮助你快速方便的绘制图表(线、面、饼、条
- 在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑。但是,从前面Stude
- PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Proje
- 需求:请求接口之后,缓存当前接口的数据,下次请求同一接口时拿缓存数据,不再重新请求添加缓存失效时间cache使用map来实现ES6 模块与
- 最近在做后台管理系统的时候遇到要使用富文本编辑器。最后选择了ueditor,我的项目使用 vue+vuex+vue-router+webpa
- 假设有如下目录结构:-- dir0| file1.py| file2.py| dir3| file3.py| dir4| file4.pyd
- python一直被病垢运行速度太慢,但是实际上python的执行效率并不慢,慢的是python用的解释器Cpython运行效率太差。“一行代
- <!doctype><html><head><title>新闻图片轮换类</title
- 引言with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ im
- Python “TypeError: unhashable type: ‘dict&rsqu
- Python 语句语句是 Python 解释器解析和处理的基本指令单元。通常解释器按顺序一个接一个的执行语句。在 REPL 会话中,语句在输
- 导语春节是中国特有的传统节日,中国结是中华民族特有的纯粹的文化精髓,富含丰富的文化底蕴,代表着我们对未来,对美好生活的向往和憧憬。新春佳节,
- 本篇阅读的代码实现了将输入的数字转化成一个列表,输入数字中的每一位按照从左到右的顺序成为列表中的一项。本篇阅读的代码片段来自于30-seco
- 本文通过实际业务系统中调整的一个案例,试图给出一个常见CPU消耗问题的一个诊断方法.大多数情况下,系统的性能问题都是由不良SQL代码引起的,
- 一、下载SQL Server 2008 R2安装文件cn_sql_server_2008_r2_enterprise_x86_x64_ia6
- 1、登录接口登录后返回对应token封装:import jsonimport requestsfrom util.operation_jso
- 本例子实现从hbase获取数据,并发送kafka。使用#!/usr/bin/env python#coding=utf-8import sy
- --创建测试表 DECLARE @Users TABLE ( ID INT IDENTITY(1,1), UserInfo XML ) --