python发送带有附件的163邮件

问题背景

在开发私人公众号,根据开发公众号的初衷需求,需要实现python脚本下发送带有附件的163邮件,实现Kindle电子书的自动化推送。 详细源码

问题解决

第一次尝试

最初的代码,使用web.py框架提供的发送邮件的代码,

web.config.smtp_server = 'smtp.gmail.com'
web.config.smtp_port = 587
web.config.smtp_username = '[email protected]'
web.config.smtp_password = 'secret'
web.config.smtp_starttls = True
# Once this configuration is set, web.sendmail can be used to send mail using the gmail account. Gmail signs all these mails.

web.sendmail('[email protected]', '[email protected]', 'subject', 'message')

但是具体试验不成功,代码路径为:http://webpy.org/cookbook/sendmail_using_gmail
后边发现原因可能在于最终调用到

smtplib.SMTP_SSL(mail_host, port=port)

的差异上,web.py调用的不是上边对应的接口,而是下述代码片段
python发送带有附件的163邮件_第1张图片

第二次尝试

既然方案不生效,那么只能找其他方法,开始在网络上一边寻找,一边试验代码是不是生效。哈哈哈,功夫不负有心人,终于还是找到可用的代码,也是通过下边的这段代码确定是接口调用的问题。参考的代码在https://blog.csdn.net/gpf951101/article/details/78909233这篇博客,
完整的代码如下:

import smtplib
from email.mime.text import MIMEText
 
def send_mail(username, passwd, recv, title, content, mail_host='smtp.163.com', port=465):
    msg = MIMEText(content)    
    msg['Subject'] = title    
    msg['From'] = username
    msg['To'] = recv            
    print 'Begin Connect...'
    smtp = smtplib.SMTP_SSL(mail_host, port=port)
    print 'Begin Login...'  
    smtp.login(username, passwd)
    print 'Begin Send...'
    smtp.sendmail(username, recv, msg.as_string()) 
    smtp.quit()  
    print('email send success.')
 
if __name__ == '__main__':
    email_user = '[email protected]' 
    email_pwd = 'xxxxx'  
    maillist = '[email protected]'
    title = 'mytitle'
    content = 'content, I comes from China!'
    send_mail(email_user, email_pwd, maillist, title, content)

@gpf951101特别感谢这位作者。上边的代码不是鄙人写的,来自上述链接。

到现在为止实现了python发送163的普通邮件,还差发送附件的功能。

第三次尝试

还是在网络上寻找,最终找到https://github.com/rootzhongfengshan/python_practical/blob/master/SentMail/SentMailWithAttachment.py
于是,最终的代码成型。来之不易,还望对诸君有所帮助。

上代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2018年12月4日

@author: chuanqin
'''

#===============================================================================
# below original code comes from the link:https://blog.csdn.net/gpf951101/article/details/78909233
# great thanks to this great man. I modify the code to suit my own project.
# also reference for attachment of email https://github.com/rootzhongfengshan/python_practical/blob/master/SentMail/SentMailWithAttachment.py
#===============================================================================

import smtplib
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from config import settings


def send_mail(recv, title, content, attachments, mail_host='smtp.163.com', port=465):
    username = settings.get(u'email section', u'email user')
    passwd = settings.get(u'email section', u'email password')
    content = '

'+content+'

WeChat Official account QCQ.

' msg = MIMEText(content, 'html') message = MIMEMultipart() message['Subject'] = title message['From'] = username message['To'] = recv message.attach(msg) for fileName in attachments: attachment = MIMEText(open(fileName, 'rb').read(), 'base64', 'utf-8') attachment["Content-Type"] = 'application/octet-stream' attachment["Content-Disposition"] = 'attachment; filename="' + fileName + '"' message.attach(attachment) try: print 'Begin Connect...' smtp = smtplib.SMTP_SSL(mail_host, port=port) print 'Begin Login...' smtp.login(username, passwd) print 'Begin Send...' smtp.sendmail(username, recv, message.as_string()) smtp.quit() print('email send success.') except Exception, exc: print exc, traceback.print_exc()

解释代码

  1. from config import settings
    这个文件中用于载入设置文件,因为,邮件的账户和密码是敏感信息,不方便直接放出来,尤其是把自己的代码用GitHub作为Host,这样上传代码的时候可以不用上传配置文件。下边是config.py代码片
import configparser
settings = configparser.ConfigParser()
settings._interpolation = configparser.ExtendedInterpolation()
settings.read('./config.ini')
print settings.sections()
print settings.get(u'email section', 'email user')

对应的config.ini文件如下,删除了敏感信息:

[email section]
email user: ********@163.com
email password: ****
  1. 突然发现其他的没什么好说的了。

尾声

祝福大家都能写出好代码。

你可能感兴趣的:(script,python源代码)