使用Python發送郵件(圖片、表格、附件) 系列一:如何發送圖片、表格等的全代碼

     本文中Part 0 + 中間任何一Part 或組合 + Part 6, 即可將內容正常發送到QQ郵箱。本文使用個人電腦和個人郵箱,對代碼進行了測試,可以正常運行。非常感謝諸位網友的共享,在寫代碼的過程中給了我很大的幫助,如果出現了問題錯誤,可以多搜索多嘗試,希望對各位有幫助。

使用Python發送郵件(圖片、表格、附件) 系列二: 同時發送圖片和附件實際案例

https://blog.csdn.net/u010652755/article/details/104321576

使用Python發送郵件(圖片、表格、附件) 系列三: 發送工作報表之透視表自動刷新數據https://blog.csdn.net/u010652755/article/details/104350889

# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 16:26:38 2020

@author: xxx
"""
import os
os.chdir(r'F:\自動化報表') # 設置文件路徑

import numpy as np
import pandas as pd

import smtplib
from email.message import EmailMessage
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


# Part 0 set initial parameter
mail_user = 'xxxxx'          # 郵箱登錄名,次處使用QQ郵箱,填寫QQ號即可,不用帶@qq.com
mail_pass = 'abcdefghijk'    # QQ郵箱授權碼,可百度如何獲取

sender    = '[email protected]'                       # 發件人
receivers = ['[email protected]', '[email protected]']  # 收件人列表,list形式
chaosong  = ['[email protected]']                     # 抄送人列表,list形式

# 設置郵件體對象
msg = MIMEMultipart()                       # 郵件體對象,此處可加入參數, 具體可百度
subject = 'python send email test'          # 郵件主題
msg['subject'] = Header(subject, 'utf-8')   # 加入郵件主題
msg['From'] = "{}".format(sender)           # 加入郵件發送人
msg['To'] = ",".join(receivers)             # 加入郵件接收人
msg['Cc'] = ",".join(chaosong)              # 加入郵件抄送人,如無,可註釋掉



# Part 1 文本內容
text_content = """This is a test email"""
textApart = MIMEText(text_content, 'plain', 'utf-8')
msg.attach(textApart)



# Part 2.1 發送單個附件
pdfFile = r"F:\自動化報表\test.pdf"
pdfName = 'test.pdf'
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfName)
msg.attach(pdfApart)


# Part 2.2 發送多個附件
files = ['temp.xlsx', 'test.pdf']
for i in np.arange(len(files)):
    attFile = MIMEApplication(open(files[i], 'rb').read())
    attFile.add_header('Content-Disposition', 'attachment', filename=files[i])
    msg.attach(attFile)


# Part 3.1 網頁內容,有鏈接,插入圖片; 如果同時發送網頁內容和純文本,只保留網頁內容。因不影響使用,未追查原因
htmlFile = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="https://www.python.org">link</a> you wanted.
    </p>
    <p>圖片演示:
    <br /><img src="cid:0", width=200, height=180  ></p>
  </body>
</html>
""" # 圖片演示下的 cid 後的內容(可能不是數字)需與 下面 imageApart.add_header('Content-ID', '<0>') 的<>內容一致
htmlApart = MIMEText(htmlFile, 'html')

# 在正文中顯示圖片
imageFile = 'trees in automn.png'
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-ID', '<0>')
msg.attach(imageApart)
msg.attach(htmlApart)

# Part 3.2 在附件中顯示圖片。Part 3.1 只能在正文顯示圖片,如果想同時將同一張圖片加入附件,可用如下代碼
attachImage = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
attachImage.add_header('Content-Disposition', 'attachment', filename=imageFile)
msg.attach(attachImage)



# Part 4 在HTML或附件中顯示多張圖片
# 網頁內容,有鏈接,插入多張圖片
htmlFile = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="https://www.python.org">link</a> you wanted.
    </p>
    <p>圖片演示flowers:
    <br /><img src="cid:0", width=200, height=180  >
    <br />第四張圖片:
    <br /><img src="cid:1", width=200, height=180  >
    <br />向陽而生的樹木:
    <br /><img src="cid:2", width=200, height=180  >
    <br />秋天的樹木:
    <br /><img src="cid:3", width=200, height=180  >
    </p>
  </body>
</html>
"""
htmlApart = MIMEText(htmlFile, 'html')

# 在正文中顯示多張圖片
images = [ i for i in os.listdir() if i.endswith(('.jpg', '.png'))] # images列表存放要發送的圖片附件,路徑已設置,見開頭,此處未用全路徑
for i in np.arange(len(images)):
    imageFile = images[i]
    imageMultiApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    imageMultiApart.add_header('Content-ID', '<%i>' % i)
    msg.attach(imageMultiApart)
msg.attach(htmlApart)

# 在附件中顯示多張圖片, 可與 part 2.2 合併
for i in np.arange(len(images)):
    imageFile = images[i]
    attachImage = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    attachImage.add_header('Content-Disposition', 'attachment', filename=imageFile)
    msg.attach(attachImage)



# Part 5
# 郵件正文中嵌入表格,比較簡單的單行單列的表格,即同一行或同一列中沒有其他合併的單元格
pd.set_option('display.max_colwidth', -1)
df = pd.read_excel('temp.xlsx', nrows=5)
# df['縮略圖'] = '<img src="' + df['縮略圖'] + '">' # 表中含有圖片鏈接時的轉換,如爲普通數據,可註釋掉
table_title = " 表格標題"

def get_html_msg(df, table_title):
    """
    1. 構造html信息
    """
    df_html = df.to_html(escape=False)

    # 表格格式
    head = \
        """
        <head>
            <meta charset="utf-8">
            <STYLE TYPE="text/css" MEDIA=screen>

                table.dataframe {
                    border-collapse: collapse;
                    border: 2px solid #a19da2;
                    /*居中顯示整個表格*/
                    margin: auto;
                }

                table.dataframe thead {
                    border: 2px solid #91c6e1;
                    background: #f1f1f1;
                    padding: 10px 10px 10px 10px;
                    color: #333333;
                }

                table.dataframe tbody {
                    border: 2px solid #91c6e1;
                    padding: 10px 10px 10px 10px;
                }

                table.dataframe tr {

                }

                table.dataframe th {
                    vertical-align: top;
                    font-size: 14px;
                    padding: 10px 10px 10px 10px;
                    color: #105de3;
                    font-family: arial;
                    text-align: center;
                }

                table.dataframe td {
                    text-align: center;
                    padding: 10px 10px 10px 10px;
                }

                body {
                    font-family: 宋體;
                }

                h1 {
                    color: #5db446
                }

                div.header h2 {
                    color: #0002e3;
                    font-family: 黑體;
                }

                div.content h2 {
                    text-align: center;
                    font-size: 28px;
                    text-shadow: 2px 2px 1px #de4040;
                    color: #fff;
                    font-weight: bold;
                    background-color: #008eb7;
                    line-height: 1.5;
                    margin: 20px 0;
                    box-shadow: 10px 10px 5px #888888;
                    border-radius: 5px;
                }

                h3 {
                    font-size: 22px;
                    background-color: rgba(0, 2, 227, 0.71);
                    text-shadow: 2px 2px 1px #de4040;
                    color: rgba(239, 241, 234, 0.99);
                    line-height: 1.5;
                }

                h4 {
                    color: #e10092;
                    font-family: 楷體;
                    font-size: 20px;
                    text-align: center;
                }

                td img {
                    /*width: 60px;*/
                    max-width: 300px;
                    max-height: 300px;
                }

            </STYLE>
        </head>
        """

    # 構造正文表格
    body = \
        """
        <body>

        <div align="center" class="header">
            <!--標題部分的信息-->
            <h1 align="center">{table_title}</h1>
        </div>

        <hr>

        <div class="content">
            <!--正文內容-->
            <h2>帶圖片展示的表格</h2>

            <div>
                <h4></h4>
                {df_html}

            </div>
            <hr>

            <p style="text-align: center"> </p>
        </div>
        </body>
        """.format(df_html=df_html, table_title=table_title)

    html_msg= "<html>" + head + body + "</html>"
#   這裏是將HTML文件輸出,作爲測試的時候,查看格式用的,正式腳本中可以註釋掉
#   fout = open('test.html', 'w', encoding='UTF-8', newline='')
#   fout.write(html_msg)
    return html_msg

# html 內容
html_msg = get_html_msg(df, table_title)
content_html = MIMEText(html_msg, "html", "utf-8")
msg.attach(content_html)



# Part 6 發送郵件,參數設置
sftp_obj = smtplib.SMTP_SSL(host='smtp.qq.com', port = 465)
sftp_obj.login(mail_user, mail_pass)
sftp_obj.sendmail(sender, receivers, msg.as_string())
sftp_obj.quit()
sftp_obj.close()
print('\nThe email has been sent successfully')
del msg

 

發佈了25 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章