python發送帶附件的郵件

今天面要用將gradle打包的apk郵件發送給某些成員,jenkins自帶的郵件沒有這個功能,我就想本身實現一個以備後用,因而仍是用我喜歡的python實現了一個: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
}

而後就是郵件發送的實現方法:app

# -*-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
相關文章
相關標籤/搜索