一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2015-09-22 编辑:简简单单 来源:一聚教程网

一,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"

热门栏目