Python 基於Python實現郵件發送

基於Python實現郵件發送html

 

by:授客 QQ1033553122python

測試環境:sql

Python版本:Python 2.7服務器

 

注:須要修改mimetypes.py文件(該文件可經過文章底部的網盤分享鏈接獲取),不然會報錯,相似以下app

mimetypes.guess_type 'ascii' codec can't decode byte 0xb0 in position 1: ord測試

 

 

實現功能:ui

郵件發送,支持文字,音頻文件,文本文件,圖形文件,應用程序及其它類型文件的發送;spa

支持不一樣的郵箱;code

支持一次性往多個郵箱發送;orm

支持一次性發送n個附件;

支持中文命名的附件發送;

 

效果:

 

 

 


 

mail.conf配置:

[SMTP]
login_user = laiyuhenshuai@163.com
login_pwd = xxxxx
from_addr =  laiyuhenshuai@163.com
to_addrs = ['mrxxx@163.com','1033553122@qq.com']

host = smtp.163.com
port = 25
 

說明:不一樣類型的郵箱(發件人郵箱),須要修改配置文件爲對應的host和端口

smtp.163.com:25

smtp.qq.com:465

 

 

實踐代碼:

#!/usr/bin/env python
# -*- coding:GBK -*-
__author__ = 'shouke'
 
import ConfigParser
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.application import MIMEApplication
import mimetypes
import os
 
class MyMail:
    def __init__(self, mail_config_file):
        config = ConfigParser.ConfigParser()
        config.read(mail_config_file)
 
        self.smtp = smtplib.SMTP()
        self.login_user = config.get('SMTP', 'login_user')
        self.login_pwd = config.get('SMTP', 'login_pwd')
        self.from_addr = config.get('SMTP', 'from_addr')
        self.to_addrs = config.get('SMTP', 'to_addrs')
        self.host = config.get('SMTP', 'host')
        self.port = config.get('SMTP', 'port')
 
    # 鏈接到服務器
    def connect(self):
        self.smtp.connect(self.host, self.port)
 
    # 登錄郵件服務器
    def login(self):
        try:
            self.smtp.login(self.login_user, self.login_pwd)
        except Exception as e:
            print('%s' % e)
 
    # 發送郵件
    def send_mail(self, mail_subject, mail_content, attachment_path_set):
         # 構造MIMEMultipart對象作爲根容器
        msg = MIMEMultipart()
        msg['From'] = self.from_addr
        # msg['To'] = self.to_addrs        
    msg['To'] = ','.join(eval_r(self.to_addrs))
        msg['Subject'] = mail_subject
 
        # 添加郵件內容
        content = MIMEText(mail_content, _charset='gbk')
        msg.attach(content)
 
        for attachment_path in attachment_path_set:
            if os.path.isfile(attachment_path): # 若是附件存在
                type, coding = mimetypes.guess_type(attachment_path)
                if type == None:
                    type = 'application/octet-stream'
 
                major_type, minor_type = type.split('/', 1)
                with open(attachment_path, 'rb') as file:
                    if major_type == 'text':
                        attachment = MIMEText(file.read(), _subtype=minor_type)
                    elif major_type == 'image':
                        attachment = MIMEImage(file.read(),  _subtype=minor_type)
                    elif major_type == 'application':
                        attachment = MIMEApplication(file.read(), _subtype=minor_type)
                    elif major_type == 'audio':
                        attachment = MIMEAudio(file.read(), _subtype=minor_type)
 
                # 修改附件名稱
                attachment_name = os.path.basename(attachment_path)
                attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))
 
                msg.attach(attachment)
 
        # 獲得格式化後的完整文本
        full_text = msg.as_string()
 
        # 發送郵件
        self.smtp.sendmail(self.from_addr, eval_r(self.to_addrs), full_text)
 
    # 退出
    def quit(self):
        self.smtp.quit()
 
if __name__ == '__main__':
    mymail = MyMail('./mail.conf')
    mymail.connect()
    mymail.login()
    mail_content = 'hello,親,這是一封測試郵件,收到請回復^^ 2014'
    mymail.send_mail('郵件標題--親,收到一份郵件,請及時查收', mail_content, {'d:\\shouke.csv', 'd:\\2345haoya_3.1.1.9229.exe',
                                              'd:\\shouke.ini','d:\\shouke.ini', 'd:\\test.mp3', 'd:\\test.png', 'd:\\report20150507204645.html',
                                              'd:\\1 - 副本.sql'})
    mymail.quit()

 

pdf版本及mimetypes.py下載地址: http://pan.baidu.com/s/1P3C3W

相關文章
相關標籤/搜索