python smtp 发邮件 添加附件
# -*- coding:utf-8 -*-
# __author__ = 'justing' import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication SENDER = "xxx"
PASSWD = "xxx"
SMTPSERVER = "xxx" class Mail(object):
"""
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
注意:邮箱必须开启SMTP才可以通过该脚本发邮件 MIMEBase
|-- MIMENonMultipart
|-- MIMEApplication
|-- MIMEAudio
|-- MIMEImage
|-- MIMEMessage
|-- MIMEText
|-- MIMEMultipart
一般来说,不会用到MIMEBase,而是直接使用它的继承类。MIMEMultipart有attach方法,而MIMENonMultipart没有,只能被attach。
MIME有很多种类型,这个略麻烦,如果附件是图片格式,我要用MIMEImage,如果是音频,要用MIMEAudio,如果是word、excel,我都不知道该用哪种MIME类型了,得上google去查。
最懒的方法就是,不管什么类型的附件,都用MIMEApplication,MIMEApplication默认子类型是application/octet-stream。
"""
def __init__(self, receivers, subject, content, content_type=None, attachment=None, sender=SENDER, passwd=PASSWD,
smtp_server=SMTPSERVER):
self.sender = sender
self.passwd = passwd
self.smtp_server = smtp_server
#receivers type list
self.receivers = receivers
self.subject = subject
self.content = content
self.content_type = content_type
#attachement type is list or str
self.attachment = attachment def attach(self, path):
filename = os.path.basename(path)
with open(path, 'rb') as f:
info = f.read()
attach_part = MIMEApplication(info)
attach_part.add_header('Content-Disposition', 'attachment', filename=filename)
self.msg.attach(attach_part) def handle_attachment(self):
# 支持多个附件
if isinstance(self.attachment, list):
for path in self.attachment:
self.attach(path)
if isinstance(self.attachment, str):
self.attach(path) def handle(self): if not self.content_type or self.content_type == "text":
text = MIMEText(self.content, 'plain', 'utf-8') elif self.content_type == "html":
text = MIMEText(self.content, _subtype='html', _charset='utf-8')
else:
raise "type only support utf and text"
self.msg.attach(text)
if self.attachment:
self.handle_attachment() def send(self):
# 如名字所示: Multipart就是多个部分
self.msg = MIMEMultipart()
self.msg['From'] = self.sender
#msg['To']接收的是字符串而不是list,如果有多个邮件地址,用,分隔即可。
self.msg['To'] = ','.join(self.receivers)
self.msg['Subject'] = self.subject
self.handle() try:
server = smtplib.SMTP(self.smtp_server)
#set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
#server.set_debuglevel(1) server.ehlo()
#加密:调用starttls()方法,就创建了安全连接
server.starttls()
server.login(self.sender, self.passwd)
#self.receivers type list
server.sendmail(self.sender, self.receivers, self.msg.as_string())
server.quit()
except Exception, e:
print "fail to send mail:{}".format(e) receivers = ['xxx@lenovo.com', 'xxx@qq.com']
subject = "This is a TEST"
content = "hello kitty"
content_type = "html"
path = r"D:\workspace\script"
attachment = []
# for parent_dir, child_dirs, filenames in os.walk(path):
# print "parent_dir>>", parent_dir
# print "filenames", filenames # for filename in filenames:
# if filename.split(".")[-1] in ["jpg", "xlsx", "mp3", "png"]:
# attachment.append(os.path.join(parent_dir, filename)) mail = Mail(receivers, subject, content, content_type, attachment)
mail.send()
python smtp 发邮件 添加附件的更多相关文章
- python SMTP发邮件
# from email.mime.text import MIMEText from email.header import Header import smtplib # sender = 'zc ...
- python smtp发邮件报错“[Errno -2] Name or service not known”的解决
最近给ss-py-mu写了个检查用户是否到期,并在到期前的第2天邮件提醒的功能. 配置存储在ini文件中,通过configparser模块获取,但尝试发送邮件的时候发现报错[Errno -2] Nam ...
- python基础-发邮件smtp
先来想下发送邮件需要填写什么,还需要有什么条件1.与邮件服务器建立连接,用户名和密码2.发邮件:发件人,收件人,主题,内容,附件3.发送 使用第三方邮箱发送邮件 #! /usr/bin/env pyt ...
- python webdriver 登录163邮箱发邮件加附件, 外加数据和程序分离,配置文件的方式
配置文件:UiObjectMapSendMap.ini用来存放配置信息 GetOptionSendMail.py 用来读取配信息 #encoding=utf-8from selenium.webdri ...
- python自动发邮件总结及实例说明
python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用.smtplib模块主要负责发送邮件,email模块主要负责构造邮件. sm ...
- 【Python系列】Python自动发邮件脚本-html邮件内容
缘起 这段时间给朋友搞了个群发邮件的脚本,为了防止进入垃圾邮件,做了很多工作,刚搞完,垃圾邮件进入率50%,觉得还不错,如果要将垃圾邮件的进入率再调低,估计就要花钱买主机了,想想也就算了,先发一个月, ...
- python自动发邮件库yagmail
#### 一般发邮件方法 我以前在通过Python实现自动化邮件功能的时候是这样的: import smtplib from email.mime.text import MIMEText from ...
- 【Python】 发邮件用 smtplib & email
smtplib & email ■ 概述 发邮件主要用到smtplib以及email模块.stmplib用于邮箱和服务器间的连接,发送的步骤.email模块主要用于处理编码,邮件内容等等.主要 ...
- python自动发邮件库yagmail(转)
一般发邮件方法 我以前在通过Python实现自动化邮件功能的时候是这样的: import smtplib from email.mime.text import MIMEText from email ...
随机推荐
- JAVA 调用https接口, java.security.cert.CertificateException
package com.easycare.store.util; import java.security.cert.CertificateException; import java.securit ...
- xmind-HTTP协议
- python模拟鼠标键盘操作 GhostMouse tinytask 调用外部脚本或程序 autopy右键另存为
0.关键实现:程序窗口前置 python 通过js控制滚动条拉取全文 通过psutil获取pid窗口句柄,通过win32gui使程序窗口前置 通过pyauto实现右键菜单和另存为操作 1.参考 aut ...
- UOJ#218. 【UNR #1】火车管理 线段树 主席树
原文链接https://www.cnblogs.com/zhouzhendong/p/UOJ218.html 题解 如果我们可以知道每次弹出栈之后新的栈顶是什么,那么我们就可以在一棵区间覆盖.区间求和 ...
- 使用Python下载文件
python -c "with open('/tmp/file.sh', 'wb') as f: import urllib2; f.write(urllib2.urlopen('http: ...
- CSS-Sass
什么是css预处理器
- C# 数据为空,不能对NULL调用此方法或属性的解决办法
在运行C#项目时,报出了以下错误,错误原因是数据库中的值为null时,查询时会触发该错误提示 部分源代码如下: public List<Student> findData2() { ; / ...
- 学习 Vim —— Vimtutor 总结笔记
Lesson 2 2.1-2.3 删除 [dw] 删除从光标开始处至下一词开始前的部分,光标停在下一词的词首. [de] 删除从光标开始处至词尾的部分. [d$] 删除从光标开始处至行末的部分. 2. ...
- flask之wtforms
本篇导航: wtforms组件的使用 自定义From组件 一.wtforms组件的使用 1.flask中的wtforms WTForms是一个支持多个web框架的form组件,主要用于对用户请求数据进 ...
- 1. js数据类型_对象_函数_内存
1. js数据类型有哪些? 基本(值)类型 Number ---- 任意数值 String ---- 任意字符串 Boolean ---- true/false undefined ---- unde ...