# -*- 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. Eclipse Oxygen.2 Release (4.7.2)添加JUnit

    在project节点上右击,Build Path->Add Libraries->JUnit

  2. [原创]基于Zynq AXI-Bram Standalone & Linux 例程

    基于Zynq AXI-Bram Standalone & Linux 例程 待添加完善中

  3. UIWebView的常用方法

    //webview导航栏类型enum UIWebViewNavigationType : Int { case LinkClicked case FormSubmitted case BackForw ...

  4. James Munkres Topology: Theorem 16.3

    Theorem 16.3 If \(A\) is a subspace of \(X\) and \(B\) is a subspace of \(Y\), then the product topo ...

  5. Javascript 精简语法介绍

    1. 取整同时转成数值型: '10.567890'|0 结果: 10 '10.567890'^0 结果: 10 -2.23456789|0 结果: -2 ~~-2.23456789 结果: -2 2. ...

  6. sort it 树状数组+逆序对

    sum[i]是1-i所有1的和,而i-sum[a[i]]就是在a[i]后面的数,即在i之前出现,却比他大的数.1是加在a[i]上,即i实际应该放的位置.而c[i]是为sum做准备的 #include& ...

  7. 一次国际化记录以及平铺JSON数据

    ​ 写这个方法的原因是因为我们需要改版国际化,因为相同的项目有其他分支做过国际化,但是主版本没有进行过国际化,目前需要修改主版本的国际化,但是因为国际化的方式做了结构上的调整所以写了这个工具方法方便去 ...

  8. FZU 2285 迷宫寻宝

    思路: bfs求最短路径. #include<stdio.h> #include<iostream> #include<queue> #include<cst ...

  9. 洛谷.3733.[HAOI2017]八纵八横(线性基 线段树分治 bitset)

    LOJ 洛谷 最基本的思路同BZOJ2115 Xor,将图中所有环的异或和插入线性基,求一下线性基中数的异或最大值. 用bitset优化一下,暴力的复杂度是\(O(\frac{qmL^2}{w})\) ...

  10. 一文搞定scrapy爬取众多知名技术博客文章保存到本地数据库,包含:cnblog、csdn、51cto、itpub、jobbole、oschina等

    本文旨在通过爬取一系列博客网站技术文章的实践,介绍一下scrapy这个python语言中强大的整站爬虫框架的使用.各位童鞋可不要用来干坏事哦,这些技术博客平台也是为了让我们大家更方便的交流.学习.提高 ...