1. 程式人生 > >Python smtplib傳送郵件 包含文字、附件、圖片等

Python smtplib傳送郵件 包含文字、附件、圖片等


解決之前版本的問題,下面為最新版
#!/usr/bin/env python
# coding:gbk

"""
FuncName: sendemail.py
Desc: sendemail with text,image,audio,application...
Date: 2016-06-20 10:30
Home: http://blog.csdn.net/z_johnny
Author: johnny
"""

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.utils import COMMASPACE
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
import ConfigParser
import smtplib
import os

class MyEmail:
    def __init__(self, email_config_path, email_attachment_path):
        """
        init config
        """
        config = ConfigParser.ConfigParser()
        config.read(email_config_path)
        self.attachment_path = email_attachment_path

        self.smtp = smtplib.SMTP()
        self.login_username = config.get('SMTP', 'login_username')
        self.login_password = config.get('SMTP', 'login_password')
        self.sender = config.get('SMTP', 'login_username')    # same as login_username
        self.receiver = config.get('SMTP', 'receiver')
        self.host = config.get('SMTP', 'host')
        #self.port = config.get('SMTP', 'port')        發現加入埠後有時候發郵件出現延遲,故暫時取消

    def connect(self):
        """
        connect server
        """
        #self.smtp.connect(self.host, self.port)
        self.smtp.connect(self.host)

    def login(self):
        """
        login email
        """
        try:
            self.smtp.login(self.login_username, self.login_password)
        except:
            raise AttributeError('Can not login smtp!!!')

    def send(self, email_title, email_content):
        """
        send email
        """
        msg = MIMEMultipart()                   # create MIMEMultipart
        msg['From'] = self.sender              # sender
        receiver = self.receiver.split(",")     # split receiver to send more user
        msg['To'] = COMMASPACE.join(receiver)
        msg['Subject'] = email_title           # email Subject
        content = MIMEText(email_content, _charset='gbk')   # add email content  ,coding is gbk, becasue chinese exist
        msg.attach(content)

        for attachment_name in os.listdir(self.attachment_path):
            attachment_file = os.path.join(self.attachment_path,attachment_name)

            with open(attachment_file, 'rb') as attachment:
                if 'application' == 'text':
                    attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
                elif 'application' == 'image':
                    attachment = MIMEImage(attachment.read(),  _subtype='octet-stream')
                elif 'application' == 'audio':
                    attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
                else:
                    attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')

            attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))
            # make sure "attachment_name is chinese" right
            msg.attach(attachment)

        self.smtp.sendmail(self.sender, receiver, msg.as_string())    # format  msg.as_string()

    def quit(self):
        self.smtp.quit()

def send():
    import  time
    ISOTIMEFORMAT='_%Y-%m-%d_%A'
    current_time =str(time.strftime(ISOTIMEFORMAT))

    email_config_path = './config/emailConfig.ini'    # config path
    email_attachment_path = './result'                # attachment path
    email_tiltle = 'johnny test'+'%s'%current_time    # as johnny test_2016-06-20_Monday ,it can choose only file when add time
    email_content = 'python傳送郵件測試,包含附件'

    myemail = MyEmail(email_config_path,email_attachment_path)
    myemail.connect()
    myemail.login()
    myemail.send(email_tiltle, email_content)
    myemail.quit()

if __name__ == "__main__":
    # from sendemail import SendEmail
    send()


配置檔案 emailConfig.ini

路徑要與程式對應

;login_username : 登陸發件人使用者名稱

;login_password : 登陸發件人密碼

;host:port : 發件人郵箱對應的host和埠,如:smtp.163.com:25 和 smtp.qq.com:465

;receiver : 收件人,支援多方傳送,格式(注意英文逗號): [email protected],[email protected]


[SMTP]
login_username = [email protected]

login_password = johnny

host = smtp.163.com

port = 25

receiver = 
[email protected]
,[email protected],[email protected]


之前版本出現的問題:

#!/usr/bin/env python
#coding: utf-8

'''
FuncName: smtplib_email.py
Desc: 使用smtplib傳送郵件
Date: 2016-04-11 14:00
Author: johnny
'''

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import COMMASPACE,formatdate
from email import encoders

def send_email_text(sender,receiver,host,subject,text,filename):
	
    assert type(receiver) == list

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = COMMASPACE.join(receiver)
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(text))                 #郵件正文內容

    for file in filename:                      #郵件附件
        att = MIMEBase('application', 'octet-stream') 
        att.set_payload(open(file, 'rb').read())
        encoders.encode_base64(att)
        if file.endswith('.html'):             # 若不加限定,jpg、html等格式附件是bin格式的 
            att.add_header('Content-Disposition', 'attachment; filename="今日測試結果.html"')          # 強制命名,名稱未成功格式化,如果可以解決請聯絡我
        elif file.endswith('.jpg') or file.endswith('.png') :
            att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"')
        else:
            att.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
        msg.attach(att)

    smtp = smtplib.SMTP(host)          
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(username,password)
    smtp.sendmail(sender,receiver, msg.as_string())
    smtp.close()

if __name__=="__main__":
    sender = '
[email protected]
' receiver = ['[email protected]'] subject = "測試" text = "johnny'lab test" filename = [u'測試報告.html','123.txt',u'獲取的資訊.jpg'] host = 'smtp.163.com' username = '[email protected]' password = 'qqq' send_email_text(sender,receiver,host,subject,text,filename)


已測試通過,使用Header並沒有變成“頭”,故未使用

若能解決附件格式為(html、jpg、png)在郵箱附件中格式不為“bin”的請聯絡我,希望此對大家有所幫助,謝謝(已解決,見上面最新版

Python 郵件smtplib傳送示例    請點選我傳送