SMTP協議完成Python自動向郵箱發送郵件(文本、html、圖片、附件)

                             Python自動發送郵件(文本、html、圖片、附件)

     本文由博主經過查閱網上資料整理總結後編寫,如存在錯誤或不恰當之處請留言以便更正,內容僅供大家參考學習。


Python自動發送郵件

1.開啓郵箱SMTP服務

SMTP是發送郵件的協議,Python內置對SMTP的支持,可以發送純文本郵件、HTML郵件以及帶附件的郵件。

2.獲得郵箱登錄授權碼 

授權碼是QQ郵箱推出的,用於登錄第三方客戶端的專用密碼,在第三方客戶端的密碼框裏面是輸入16位授權碼而不是郵箱密碼。

sicnfytnnhukbagg

3.導入使用的模塊 

smtplib和email,這倆模塊是python自帶的,只需import即可使用;smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件

4. 向郵箱發送文字

創建SMTP對象-->連接到SMTP服務器-->登錄SMTP服務器-->構建郵件內容-->發送郵件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def send_email(SMTP_host, from_account, from_password, to_account, subject, content):
    # 1. 實例化SMTP,創建對象
    smtp = smtplib.SMTP()
    # 2. 鏈接郵件服務器,若爲QQ:smtp.qq.com;若爲163:smtp.163.com
    smtp.connect(SMTP_host)
    # 3. 配置發送郵箱的用戶名和密碼(授權碼)
    smtp.login(from_account, from_password)
    # 4. 配置發送內容msg
    msg = MIMEText(content, 'plain', 'utf-8')  # 內容
    msg['Subject'] = Header(subject,'utf-8')  # 主題
    msg['From'] = from_account
    msg['To'] = to_account
    # 5. 配置發送郵箱,接受郵箱,以及發送內容
    smtp.sendmail(from_account, to_account, msg.as_string())
    # 6. 關閉郵件服務
    smtp.quit()

if __name__ == '__main__':
    try:
        send_email("smtp.qq.com", "[email protected]", "sicnfytnnhukbagg", "[email protected]", "I want to talk to u",
                   "In this semester")
        print("郵件發送成功")
    except smtplib.SMTPException:
        print("Error: 無法發送郵件")

補充解釋

①. connect(host,port)-->  host:指定連接的郵箱服務器。常用郵箱的smtp服務器地址如下:新浪郵箱:smtp.sina.com,qq郵箱:smtp.qq.com,搜狐郵箱:smtp.sohu.com,126郵箱:smtp.126.com,139郵箱:smtp.139.com,163網易郵箱:smtp.163.com。port:指定連接服務器的端口號,默認爲0.

②. login(user,password)-->user:登錄郵箱的用戶名。password:登錄郵箱的授權碼

③ sendmail(from_addr,to_addrs,msg,...)-->from_addr:郵件發送者地址。to_addrs:郵件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'。msg:發送消息:郵件內容。一般是msg.as_string():as_string()是將msg(MIMEText對象或者MIMEMultipart對象)變爲str。

④.quit(): 用於結束SMTP會話。

5.向郵箱發送圖片

如果構造一個MIMEText對象,就表示一個文本郵件對象

如果構造一個MIMEImage對象,就表示一個作爲附件的圖片

要把多個對象組合起來,就用MIMEMultipart對象

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

def send_email_imag(SMTP_host, from_account, from_password, to_account, subject, img_data):
    html_content = """
    <html><body>
    <img src="cid:image1" alt="image1" align="center" width=100% >
    </body></html>
    """
    # 1. 實例化SMTP,鏈接郵件服務器(也可以使用上面的方法)
    smtp = smtplib.SMTP_SSL(SMTP_host, port=465)
    # 2. 登錄郵箱,用戶名和密碼(授權碼)
    smtp.login(from_account, from_password)
    print('Login Successful!')
    # 3. 配置發送內容msg
    msg = MIMEMultipart()
    # 3.1 創建超文本對象(用來確定圖片佈局) ,並將超文本加載到msg
    content = MIMEText(html_content, _subtype='html', _charset='utf8')
    msg.attach(content)
    # 3.2 創建圖片對象,並將圖片加載到msg
    img = MIMEImage(img_data, _subtype='octet-stream')
    img.add_header('Content-ID', 'image1')
    msg.attach(img)
    # 3.3 加載郵件主題和發送賬戶
    msg['Subject'] = Header(subject, 'utf-8')  # 主題
    msg['From'] = from_account
    msg['To'] = to_account
    # 4. 配置發送郵箱,接受郵箱,以及發送內容
    smtp.sendmail(from_account, to_account, msg.as_string())
    # 5. 關閉郵件服務
    smtp.quit()


if __name__ == '__main__':
    #  相對路徑和絕對路徑
    img_file = open("123.png", "rb")
    # img_data2 = open("C:\\Users\\cqfdcw\\Desktop\\456.png","rb").read()
    img_data= img_file.read()
    img_file.close()
    try:
        send_email_imag('smtp.qq.com', '[email protected]', 'sicnfytnnhukbagg', '[email protected]', '測試發送圖片', img_data)
        print("郵件發送成功")
    except smtplib.SMTPException:
        print("Error: 無法發送郵件")

6.向郵箱發送附件

使用MIMEMultipart來標示這個郵件是多個部分組成的,然後attach各個部分。如果是附件,則add_header加入附件的聲明。

不管什麼類型的附件,都用MIMEApplication

import smtplib
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

def send_email_accessory(SMTP_host, from_account, from_password, to_account):
    # 1. 實例化SMTP,鏈接郵件服務器(也可以使用上面的方法)
    smtp = smtplib.SMTP_SSL(SMTP_host, port=465)
    # 2. 登錄郵箱,用戶名和密碼(授權碼)
    smtp.login(from_account, from_password)
    print('Login Successful!')
    # 3. 配置發送內容msg
    msg = MIMEMultipart()
    # 3.1 配置發送文本內容
    content = 'hello, this is email content.'
    textApart = MIMEText(content, 'plain', 'utf-8')
    msg.attach(textApart)
    # 3.2 配置發送圖片附件
    imageFile = '123.png'
    imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
    msg.attach(imageApart)
    # 3.3 配置發送PDF附件
    pdfFile = 'C:\\Users\\cqfdcw\\Desktop\\789.pdf'
    pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
    pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
    msg.attach(pdfApart)
    # 3.4 配置發送壓縮包附件
    zipFile = 'C:\\Users\\cqfdcw\\Desktop\\456.zip'
    zipApart = MIMEApplication(open(zipFile, 'rb').read())
    zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
    msg.attach(zipApart)
    # 3.5 配置發送word附件
    docFile = 'C:\\Users\\cqfdcw\\Desktop\\369.docx'
    docApart = MIMEApplication(open(docFile, 'rb').read())
    docApart.add_header('Content-Disposition', 'attachment', filename=docFile)
    msg.attach(docApart)
    # 3.6 配置郵件主題和發送賬戶
    subject = '這是一個郵件添加壓縮包測試'
    msg['Subject'] = Header(subject, 'utf-8')  # 主題
    msg['From'] = from_account
    # 4. 配置發送內容msg
    smtp.sendmail(from_account, to_account, msg.as_string())
    # 5. 關閉郵件服務
    smtp.quit()


if __name__ == '__main__':
    try:
        send_email_accessory('smtp.qq.com', '[email protected]', 'sicnfytnnhukbagg', ['[email protected]', ])
        print('郵件發送成功')
    except smtplib.SMTPException as e:
        print('error:', e)

7.向郵箱發送文本、html、圖片、附件等

import smtplib
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


# 下面的發件人,收件人是用於郵件傳輸的。
SMTP_host = 'smtp.qq.com'
from_account = '[email protected]'
from_password = 'sicnfytnnhukbagg'
to_account = ['[email protected]', ]
subject = 'Python email test'
# 1. 實例化SMTP,鏈接郵件服務器(也可以使用上面的方法)
smtp = smtplib.SMTP_SSL(SMTP_host, port=465)
# 2. 登錄郵箱,用戶名和密碼(授權碼)
smtp.login(from_account, from_password)
print("登錄成功")
# 3. 配置發送內容msg
msg = MIMEMultipart()
# 3.1構造文字內容
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)
# 3.2構造圖片鏈接
sendimagefile = open(r'C:\Users\cqfdcw\Desktop\456.png', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image)
# 3.3構造html
html = """
<html>  
  <head></head>  
  <body>  
    <p>Hi!<br>  
       How are you?<br>  
       Here is the <a href="http://www.baidu.com">link(http://www.baidu.com)</a> you wanted.<br> 
    </p> 
  </body>  
</html>  
"""
text_html = MIMEText(html, 'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'
msg.attach(text_html)
# 3.4構造附件(方式1)
sendfile = open(r'C:\Users\cqfdcw\Desktop\789.txt', 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
msg.attach(text_att)
# 3.4 構造附件(方式2)
zipFile = 'C:\\Users\\cqfdcw\\Desktop\\456.zip'
zipApart = MIMEApplication(open(zipFile, 'rb').read())
zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
msg.attach(zipApart)
# 3.5 配置郵件主題和發送賬戶
msg['Subject'] = Header(subject, 'utf-8')  # 主題
msg['From'] = from_account
# 4 發送郵件
smtp.sendmail(from_account, to_account, msg.as_string())
print("發送成功")
# 5. 關閉郵件服務
smtp.quit()

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章