Python中使用SMTP发送邮件的例子

一,SMTP发送邮件

这里PYTHON脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱.
QQ邮箱利用的是加密STMP, 需要加密版本的童鞋请关注随后的更新.
TIPS: 我的本地环境是MAC系统, Windows环境需要修改相应的字符编码.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass
# Build a new attach instance
msg = MIMEMultipart()
# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with attachments'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.126.com"  
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "126.com" 
# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名,这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)
  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s<%s@%s>" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)
    # send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')
    try:  
        server = smtplib.SMTP()
        server.set_debuglevel(1) 
        server.connect(SMTP_server)  
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False

if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure"

二,SMTP(SSL)发送邮件

这里需要注意的是大家使用QQ邮箱(SMTL over SSL)时, 需要首先在其网页客户端后台打开SMTP/POP服务, 并且设置QQ邮箱独立密码作为SMTP登陆密码, 这样在使用MUA时就不会报Authentication failed的错误.
QQ邮箱 POP3端口: 995 SMTP端口: 587
密码使用QQ邮箱独立密码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass
# Build a new attach instance
msg = MIMEMultipart()
# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with pic attachment'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.qq.com"  
SMTP_port = "587"
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "qq.com" 
# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名,这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)
  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s<%s@%s>" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)
    # Send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')
    try:  
        server = smtplib.SMTP(SMTP_server, SMTP_port)
        server.starttls()
        server.set_debuglevel(1)   
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False

if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure"

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索python
, 密码
邮件
python smtp发送邮件、python3 smtp发送邮件、python 接收邮件smtp、python smtp发送图片、php smtp发送邮件,以便于您获取更多的相关知识。

时间: 2024-07-29 09:44:08

Python中使用SMTP发送邮件的例子的相关文章

在asp.NET 中使用SMTP发送邮件的实现代码

核心代码:复制代码 代码如下: public class Mail { #region 邮件参数 static public string accountName = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountName"]; static public string password = System.Configuration.ConfigurationManager.AppSettings[&

在asp.NET 中使用SMTP发送邮件的实现代码_实用技巧

核心代码: 复制代码 代码如下: public class Mail { #region 邮件参数 static public string accountName = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountName"]; static public string password = System.Configuration.ConfigurationManager.AppSettings[

Python 中方法参数 * 和 ** 的例子

在Python中* 和 ** 有特殊含义,他们与函数有关,在函数被调用时和函数声明时有着不同的行为.此处*号不代表C/C++的指针. 其中 * 表示的是元祖或是列表,而 ** 则表示字典 以下为 ** 的例子: 01 #--------------------第一种方式----------------------# 02 import httplib 03 def check_web_server(host,port,path): 04  h = httplib.HTTPConnection(h

Python中的CURL PycURL使用例子_python

在Linux上有个常用的命令 curl(非常好用),支持curl的就是大名鼎鼎的libcurl库:libcurl是功能强大的,而且是非常高效的函数库.libcurl除了提供本身的C API之外,还有多达40种编程语言的Binding,这里介绍的PycURL就是libcurl的Python binding.在Python中对网页进行GET/POST等请求,当需要考虑高性能的时候,libcurl是非常不错的选择,一般来说会比liburl.liburl2快不少,可能也会比Requests的效率更高.特

Python中的集合类型操作符例子

(1)标准类型操作符(所有的集合类型) 成员关系 (in, not in)         就序列而言,Python中的in和not in操作符决定某个元素是否是一个集合中的成员. 集合等价/不等价         等价/不等价被用于在相同或不同的集合之间做比较.两个集合相等是指,对每个集合而言,当且仅当其中一个集合中的每个成员同时也是另一个集合中的成员.也可以说每个集合必须是另一个集合的一个子集, 即s <= t 和s>= t 的值均为真(True),或(s <= t and s>

PYTHON中字典GET方法小例子

Python定义一个字典:dict = {'iphone':'apple','xiaomi','xiaomi','huawei':'hua'},那么我要查找键名为xiaomi对应的值,如果我们知道存在这个键,直接dict['xiaomi']就好了,但是要判断有没有这个键存在怎么办呢? 如图,判断roledict中有没有owner这个键,第一个方法:   if 'owner' in roledict:  owner = roledict['owner'] else:  owner = admin

Python实现SMTP发送邮件详细教程_python

简介 Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后面找了很久才找到原因,这都是没有一个详细的环境调试导致,所以今天特出一个详细的教程,一步一步从环境调试到代码实现整一个教程,希望对还在苦苦寻找解决方法却迟迟不能得到有效解决的人员一点帮助. SMTP协议 首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用

python中多线程的一个例子总是报错大家帮忙看看

问题描述 python中多线程的一个例子总是报错大家帮忙看看 解决方案 http://bbs.csdn.net/topics/390614709 解决方案二: ...找到原因了是t2里的args函数名没写对.............,还是谢谢各位了

PYTHON中__NEW__和__INIT__的区别例子

__NEW__和__INIT__的区别例子 Python中__new__和__init__用得最多的是__init__,__init__很像PHP,C,JAVA等其他语言中的构造方法,但是__new__也类似于构造方法,而且比__init__更早执行,它们有什么区别?怎么用? __init__ 方法是什么? 使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法通常用在初始化一个类实例的时候.例如: # -*- coding: utf-8