1. 程式人生 > >python 傳送郵件 正文中帶圖片 帶附件圖片或附件檔案例子

python 傳送郵件 正文中帶圖片 帶附件圖片或附件檔案例子

from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import encoders
import smtplib
import time


def send_mail(subject):
    email_host = ''# 伺服器地址 163郵箱"smtp.163.com"  qq郵箱"smtp.qq.com"都需要開通smtp許可權
    sender = ''  # 發件人(自己的郵箱)
    password = ''  # 密碼(自己郵箱的登入密碼)
    receiver = ''  # 收件人

    msg = MIMEMultipart()
    msg['Subject'] = subject  # 標題
    msg['From'] = ''  # 郵件中顯示的發件人別稱
    msg['To'] = ''  # ...收件人...

    signature = '''
\n\t this is auto test report!
\n\t you don't need to follow
'''
    # text = MIMEText(signature, 'plain')  # 簽名
    # msg.attach(text)

    # 正文-圖片 只能通過html格式來放圖片,所以要註釋25,26行
    mail_msg = '''
<p>\n\t this is auto test report!</p>
<p>\n\t you don't need to follow</p>
<p><a href="http://blog.csdn.net/wjoxoxoxxx">我的部落格:</a></p>
<p>截圖如下:</p>
<p><img src="cid:image1"></p>
'''
    msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定圖片為當前目錄
    fp = open(r'111.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    # 定義圖片 ID,在 HTML 文字中引用
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)

    ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    # 附件-圖片
    image = MIMEImage(open(r'111.jpg', 'rb').read(), _subtype=subtype)
    image.add_header('Content-Disposition', 'attachment', filename='img.jpg')
    msg.attach(image)
    # 附件-檔案
    file = MIMEBase(maintype, subtype)
    file.set_payload(open(r'320k.txt', 'rb').read())
    file.add_header('Content-Disposition', 'attachment', filename='test.txt')
    encoders.encode_base64(file)
    msg.attach(file)

    # 傳送
    smtp = smtplib.SMTP()
    smtp.connect(email_host, 25)
    smtp.login(sender, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print('success')

if __name_- == '__main__':
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    subject = now + 'test email'
    send_mail(subject)