>记录生活, 工作的点点滴滴...

Python 自动发送邮件

日常工作中, 很多报表需要通过邮件来发送,如日报周报等, 通过自动发送来提高效率是一个可行的方案。

于是,有了自动发送邮件的小脚本出现。

闲言少叙, 上源码(已提交至GitHub)

# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 14:00:34 2016
@author: PC
"""

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

class Mail():
    def __init__(self):
        self.__mime = MIMEMultipart('related') 
        self._bcc = []
        self.__port= 25
        self.__host='mail.host.com'
        
    @property
    def host(self):
        return self.__host
    
    @host.setter
    def host(self,host):
        self.__host = host
        
    @property
    def port(self):
        return self.__port
        
    @port.setter
    def port(self, port):
        self.__port = port
    
    def mailMsg(self, From = None, To = None, Cc = [], Subject = None):
        self.__mime['From'] = From
        self.__mime['Subject'] = Header(Subject, 'utf-8').encode()
        self.__mime['To'] = ';'.join(To)
        self.__mime['Cc'] = ';'.join(Cc)
        self._cc = Cc

    def addBcc(self, Bcc=[]):
        self._bcc = Bcc
    
    def addMailContent(self, content):
        self.__mime.attach(MIMEText(content,'html','utf-8'))
    
    def addAttachs(self, image_path=None, file_name=None ):
        if image_path != None:
            msgImage = MIMEImage(open(image_path, 'rb').read())
            msgImage.add_header('Content-ID', '<image1>') 
            self.__mime.attach()
        if file_name != None:
            attach_file = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8')
#            attach_file['Content-Type'] = 'application/octet-stream'  
#            attach_file['Content-Disposition'] = 'attachment; filename={}'.format(file_name.split('/')[-1])  
            attach_file.add_header('Content-Disposition', 'attachment',filename=('gbk', '', file_name.split('/')[-1]))
            self.__mime.attach(attach_file)
   
#    def _login(self, usr, password):
#        self.__usr = usr
#        self.__password = password
    
    def send(self, usr, password, From=None, To=[]):
        if self._bcc:
            To.extend(self._bcc)
        if self._cc:
            To.extend(self._cc)
        server = smtplib.SMTP(self.__host, self.__port)
        server.login(usr, password)
        server.sendmail(usr, To, self.__mime.as_string())
        server.quit()

if __name__ == '__main__':
    usr = 'bunshinn@126.com'
    usr = 'huyg@host.com'
    pwd = '***'
    to = ['胡<**@host.com>']
    cc = ['bu<412319433@qq.com>']
    mail = Mail()
    mail.mailMsg(From=usr, Subject='mail from py',To=to, Cc=cc)
    mail.addMailContent('hello')
#    mail.addAttachs(file_name='e:/转诊报表1215.xlsx')
    mail.send(usr=usr,password=pwd, To=to)

在一个mail实例中,

通过mailMsg方法设置主题,收件人,抄送,秘密抄送等。

通过addMailContent方法添加文件内容,实现以Html格式,可以通过style设置样式, 使内容较为美观。其中,需要注意各邮箱对Html解析的支持有所不同。

通过mail.addAttachs添加附件。

最后, mail.send实现邮件发送。


发表于:2018-01-24 17:14:07浏览(379) 评论(0) Python