python发送带附件的邮件

今天面要用将gradle打包的apk邮件发送给某些成员,jenkins自带的邮件没有这个功能,我就想自己实现一个以备后用,于是还是用我喜欢的python实现了一个:

首先习惯性的写配置:创建一个settings.py文件

# -*-coding:utf-8 -*-
import os

#邮件配置
EMAIL = {
    'host': 'smtp.mailgun.org', #邮件服务器地址
    'user': 'xxxx@qq.com', #发件用户名
    'port': 587,
    'password': 'xxxxxx', #发件人密码
    'nickname': '牛B的管理员',
    'mail_debug': True,
    'mail_ssl':True
}

然后就是邮件发送的实现方法:

# -*-coding:utf-8 -*-


import settings
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEBase
from email.mime.multipart import MIMEMultipart
import mimetypes
from email import encoders
import os
import time

# 发送带附件的邮件
def ToMail(mailto, subject, body, attachments='',  format='plain'):
    '''
    :param mailto: 发送邮件对象(发送人),可以为列表或字符串
    :param subject: 邮件标题
    :param body: 邮件主体内容
    :param attachments: 邮件附件
    :param format: 邮件页面对像
    :return: True or False
    '''
    if isinstance(body, unicode):
        body = str(body)
    me= settings.EMAIL.get('nickname') + "<"+settings.EMAIL.get('user')+">"
    msg = MIMEMultipart()
    bo = MIMEText(body, format, 'utf-8')
    if not isinstance(subject, unicode):
        subject = str(subject)
    if isinstance(mailto, list):
        msg['To'] = ";".join(mailto)
    else:
        msg['To'] = mailto
    msg.attach(bo)
    msg['Subject'] = subject
    msg['From'] = me
    msg["Accept-Language"]="zh-CN"
    msg["Accept-Charset"]="ISO-8859-1,utf-8"
    #****************************************
    #载入附件
    if isinstance(attachments, list):
        for file in attachments:
            data = open(file.decode('utf-8').encode('gbk'), 'rb')
            ctype,encoding = mimetypes.guess_type(file)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype,subtype = ctype.split('/',1)
            file_msg = MIMEBase(maintype, subtype)
            file_msg.set_payload(data.read())
            data.close()
            encoders.encode_base64(file_msg)
            #***************************************************************
            # 如果附件名称含有中文, 则 filename 要转换为gb2312编码, 否则就会出现乱码.basename.decode('utf-8').encode('gb2312')
            filename = os.path.basename(file)
            file_msg.add_header('Content-Disposition', 'attachment; filename="%s"' % filename.decode('utf8').encode('gb2312'))
            msg.attach(file_msg)
    try:
        server = smtplib.SMTP(settings.EMAIL.get('host'),
                              port=settings.EMAIL.get('port'),
                              timeout=30)
        server.debuglevel=settings.EMAIL.get('mail_debug')
        if settings.EMAIL.get('mail_ssl'):
            server.starttls()
        server.login(settings.EMAIL.get('user'),
                settings.EMAIL.get('password'))
        server.sendmail(me, mailto, msg.as_string())
        return True
    finally:
        server.close()
        return False




#**************************************************
#由于使用的国外的邮件服务器,有些不稳定所以给予三次重发机会
a = 0
while True:
    a+= 1
    if a <= 3:
        status = ToMail(['ffffff@qq.com'],
                        'aaaaaaaaaaaa',
                        'aaaaaaaaaaaaa',
                        attachments=['G:/xxx/xxx/xxxxxx.apk'])
        if status:
            break
        else:
            time.sleep(1)
    else:
        break

  

 

posted @ 2015-09-25 18:00  流浪的如影  阅读(343)  评论(0编辑  收藏  举报