# -*- 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 发邮件 添加附件的更多相关文章

  1. python SMTP发邮件

    # from email.mime.text import MIMEText from email.header import Header import smtplib # sender = 'zc ...

  2. python smtp发邮件报错“[Errno -2] Name or service not known”的解决

    最近给ss-py-mu写了个检查用户是否到期,并在到期前的第2天邮件提醒的功能. 配置存储在ini文件中,通过configparser模块获取,但尝试发送邮件的时候发现报错[Errno -2] Nam ...

  3. python基础-发邮件smtp

    先来想下发送邮件需要填写什么,还需要有什么条件1.与邮件服务器建立连接,用户名和密码2.发邮件:发件人,收件人,主题,内容,附件3.发送 使用第三方邮箱发送邮件 #! /usr/bin/env pyt ...

  4. python webdriver 登录163邮箱发邮件加附件, 外加数据和程序分离,配置文件的方式

    配置文件:UiObjectMapSendMap.ini用来存放配置信息 GetOptionSendMail.py 用来读取配信息 #encoding=utf-8from selenium.webdri ...

  5. python自动发邮件总结及实例说明

    python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用.smtplib模块主要负责发送邮件,email模块主要负责构造邮件. sm ...

  6. 【Python系列】Python自动发邮件脚本-html邮件内容

    缘起 这段时间给朋友搞了个群发邮件的脚本,为了防止进入垃圾邮件,做了很多工作,刚搞完,垃圾邮件进入率50%,觉得还不错,如果要将垃圾邮件的进入率再调低,估计就要花钱买主机了,想想也就算了,先发一个月, ...

  7. python自动发邮件库yagmail

    #### 一般发邮件方法 我以前在通过Python实现自动化邮件功能的时候是这样的: import smtplib from email.mime.text import MIMEText from ...

  8. 【Python】 发邮件用 smtplib & email

    smtplib & email ■ 概述 发邮件主要用到smtplib以及email模块.stmplib用于邮箱和服务器间的连接,发送的步骤.email模块主要用于处理编码,邮件内容等等.主要 ...

  9. python自动发邮件库yagmail(转)

    一般发邮件方法 我以前在通过Python实现自动化邮件功能的时候是这样的: import smtplib from email.mime.text import MIMEText from email ...

随机推荐

  1. 在Pycharm中自动添加时间日期作者等信息

    1.按照下面路径以此打开File→→Settings→→Editor→→File and code Templates 右侧找到Python Script,如下图 2.设置相关代码如下 ##!/usr ...

  2. Winform Focus()函数不起作用 解决办法

    private void Form_Load(object sender, EventArgs e) { this.txtName.Focus(); } 光标到不了txtName.可能的原因 TabI ...

  3. Vue中父子组件通讯——组件todolist

    一.todolist功能开发 <div id="root"> <div> <input type="text" v-model=& ...

  4. Mysql数据实时同步

    企业运维的数据库最常见的是 mysql;但是 mysql 有个缺陷:当数据量达到千万条的时候,mysql 的相关操作会变的非常迟缓; 如果这个时候有需求需要实时展示数据;对于 mysql 来说是一种灾 ...

  5. 网络安全第一集之【SQL注入:sqlmap入门】

    1,安装sqlmap和python环境 2,对于环境变量超长问题 3,使用sqlmap: sqlmap.py -u "http://k2.hlxy.net/csdw/news1.asp?dp ...

  6. String与StringBuffer

    转载于:http://www.cnblogs.com/springcsc/archive/2009/12/03/1616330.htm  l火之光 StringBuffer类和String一样,也用来 ...

  7. C# SortedDictionary以及SortedList的浅谈

    msdn叙述:The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) ...

  8. open

    open服务指的是封装的订单流接口,给外部第三方提供使用.(当然也可以区别的名字,我司这么叫而已,并且是用Java写的,谁晓得为什么不选择PHP来写)通过open api合作方就可以通过调用接口直接下 ...

  9. Python开发技术详解PDF

    Python开发技术详解(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1F5J9mFfHKgwhkC5KuPd0Pw 提取码:xxy3 复制这段内容后打开百度网盘手 ...

  10. es6学习笔记-Symbol

    概述 ES5 的对象属性名都是字符串,这容易造成属性名的冲突.比如,你使用了一个他人提供的对象,但又想为这个对象添加新的方法(mixin 模式),新方法的名字就有可能与现有方法产生冲突.如果有一种机制 ...