好久都没有更新博客了,是半年时间做了1个创业项目。失败后总结宝宝我还是老老实实打工混吃还债吧。 因为长时间做数据运营工作,报表天天见真的很烦。就想一些常规数据软件自己发算了。于是有了这个研究。
就用python3做的一个简单的自动发送脚本。定时发送邮件,还得写一个数据获取的心跳,因为是多个数据源。还有一个重要的东西是plt+pillow绘制数据仪表盘导出放到网站上,感觉偷懒技术都要上天了!
本文主要是python发邮件的!测试163,126,qq,阿里邮件推送,都可以用。
#coding=utf-8
import smtplib
import email
from email.mime.text import MIMEText #html格式邮件
from email.mime.multipart import MIMEMultipart #带图片格式邮件
from email.mime.image import MIMEImage #带图片格式邮件
# from email.mime.base import MIMEBase
# from email import encoders
# from email.mime.application import MIMEApplication
from email.header import Header
# 发件人地址,通过控制台创建的发件人地址
username = 'service@nigaea.com'
# 发件人密码,通过控制台创建的发件人密码
password = '*****'
# 自定义的回复地址
replyto = '765854380@qq.com'
# 收件人地址或是地址列表,支持多个收件人,最多30个
#rcptto = ['***', '***']
rcptto = '******'
# 构建alternative结构
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('自定义信件主题', 'utf-8')
msg['From'] = '%s <%s>' % (Header('自定义发信昵称','utf-8'), username)
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()
# 构建alternative的text/plain部分
textplain = "hello world!"
textplain = MIMEText('自定义TEXT纯文本部分','plain','utf-8')
msg.attach(textplain)
# 构建alternative的text/html部分
# texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')
# msg.attach(texthtml)
# 带附件的邮件MIMEApplication
# filename = ['简历.pdf','副本.pdf']
# fp = open(filename, 'rb')
# attachfile = MIMEApplication(fp.read())
# fp.close()
# attachfile.add_header('Content-Disposition', 'attachment', filename=filename)
# msg.attach(attachfile)
# 带多个附件的邮件MIMEApplication
# filename = ['图片.pdf','副本.pdf']
# for tmp in filename:
# fp = open(tmp, 'rb')
# attachfile = MIMEApplication(fp.read())
# fp.close()
# attachfile.add_header('Content-Disposition', 'attachment', filename=tmp)
# msg.attach(attachfile)
#带附件的邮件MIMEBase
# filename = '图片.pdf'
# attachfile = MIMEBase('application', 'octet-stream')
# attachfile.set_payload(open(filename, 'rb').read())
# attachfile.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename) )
# encoders.encode_base64(attachfile)
# msg.attach(attachfile)
# 发送邮件
try:
client = smtplib.SMTP()
#python 2.7以上版本,若需要使用SSL,可以这样创建client
#client = smtplib.SMTP_SSL()
#SMTP普通端口为25或80
client.connect('smtpdm.aliyun.com', 25)
#开启DEBUG模式
# client.set_debuglevel(0)
client.login(username, password)
#发件人和认证地址必须一致
#备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
# 使用SMTP.mail/SMTP.rcpt/SMTP.data方法
client.sendmail(username, rcptto, msg.as_string())
client.quit()
print('email send success!')
except smtplib.SMTPConnectError as e:
print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
print('邮件发送失败, ', e.message)
except Exception as e:
print('邮件发送异常, ', str(e))
这个是借鉴了阿里云邮件推送服务的实例,感觉几乎已经很好解决所需的问题。含ssl的解决方式、多个附件的、带图片的、html格式的,邮件错误类型等。可以后续自行发挥了。
作为脚本测试的化上面就已经够了,可是要每天更新数据自行发邮件还需要更多操作。网上搜索了一个很不错的类的写法,可以参考一下:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
class mailsender(object):
_from = None
_attachments = []
def __init__(self, smtpsvr, port):
self.smtp = smtplib.SMTP()
print("connecting....")
self.smtp.connect(smtpsvr, port)
print("connected!")
def login(self, user, pwd):
self._from = user
print("login ...")
self.smtp.login(user, pwd)
def add_attachment(self, filename):
att = MIMEBase('application', 'octet-stream')
att.set_payload(open(filename,'rb').read())
att.add_header('Content-Disposition', 'attachment', filename = ('gbk','',filename))
encoders.encode_base64(att)
self._attachments.append(att)
def send(self, subject, content, to_addr):
msg = MIMEMultipart('alternative')
contents = MIMEText(content, 'html', _charset ='utf-8')
msg['subject'] = subject
msg['from'] = self._from
msg['to'] = to_addr
for att in self._attachments:
msg.attach(att)
msg.attach(contents)
try:
self.smtp.sendmail(self._from, to_addr, msg.as_string())
return True
except Exception as e:
print(str(e))
return False
def close(self):
self.smtp.quit
print("logout!")
mail = mailsender('smtp.163.com','25')
mail.login('nigaea@163.com','******')
mail.add_attachment('简.pdf')
mail.send('hello test','试','buwangyouxil@163.com')
mail.close()
我的博客地址:https://www.nigaea.com/programmer/162.html