欢迎访问www.showerlee.com, 您的支持就是我前进的动力.

[Python] SMTP(SSL)发送邮件

showerlee 2015-08-27 14:33 PYTHON 阅读 (14,050) 抢沙发

这里需要注意的是大家使用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" 

正文部分到此结束
版权声明:除非注明,本文由(showerlee)原创,转载请保留文章出处!
本文链接:http://www.showerlee.com/archives/1464

继续浏览:PYTHON

还没有评论,快来抢沙发!

发表评论

icon_wink.gif icon_neutral.gif icon_mad.gif icon_twisted.gif icon_smile.gif icon_eek.gif icon_sad.gif icon_rolleyes.gif icon_razz.gif icon_redface.gif icon_surprised.gif icon_mrgreen.gif icon_lol.gif icon_idea.gif icon_biggrin.gif icon_evil.gif icon_cry.gif icon_cool.gif icon_arrow.gif icon_confused.gif icon_question.gif icon_exclaim.gif