python發送單人郵件(附件,圖片,html),多人郵件

單人郵件

# -- coding: utf-8 --
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

smtpserver = 'smtp.163.com'  # 163郵箱服務器地址
smtpport = 465  # 163郵箱ssl協議端口號
sender = '[email protected]'  # 發送者郵箱
# sender_pwd = input('請輸入密碼')#並開啓客戶端授權密碼時會設置授權碼並非登錄密碼
sender_pwd = "xxxxx"  # 授權碼自行去網頁開啓設置
rece = '[email protected]'  # 收件人郵箱
mail_username = ''

# 創建一個帶附件的郵件實例
message = MIMEMultipart()
# 編輯郵件的內容

# 往郵件容器中添加內容。這是郵件的主體
mail_title = 'python自動發郵件'
# mail_inside = MIMEText(r'這是我程序自動發送的。內含圖片', 'plain', 'utf-8')#主體文件
zhengwen = """
      各位好:

"""
mail_inside = MIMEText(zhengwen, 'plain', 'utf-8')
# 郵件的其他屬性
message['From'] = sender
message['To'] = rece
message['Subject'] = Header(mail_title, 'utf-8')
message.attach(mail_inside)

#構造附件txt附件1
attr1 = MIMEText(open(r'D:\houseinformation.txt', 'rb').read(), 'base64', 'utf-8')
attr1["content_Type"] = 'application/octet-stream'
attr1["Content-Disposition"] = 'attachment; filename="houseinformation.txt"'  # 表示這是附件,名字是啥
message.attach(attr1)

#  構造圖片附件2
att2 = MIMEText(open(r'D:\flower.jpg', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="flower.jpg"'
message.attach(att2)
# 構造html附件
att3 = MIMEText(open('report_test.html', 'rb').read(), 'base64', 'utf-8')
att3["Content-Type"] = 'application/octet-stream'
att3["Content-Disposition"] = 'attachment; filename="report_test.html"'
message.attach(att3)
try:
    smtpobj = smtplib.SMTP_SSL(smtpserver, port=smtpport)
    smtpobj.login(sender, sender_pwd)
    smtpobj.sendmail(sender, rece, message.as_string())
    print('郵件發送成功')
    smtpobj.quit()
except:
    print("郵件發送失敗")

多人郵件

import smtplib
from email.header import Header  # 用來設置郵件頭和郵件主題
from email.mime.text import MIMEText  # 發送正文只包含簡單文本的郵件,引入MIMEText即可

# 發件人和收件人
sender = '[email protected]'

# 所使用的用來發送郵件的SMTP服務器
smtpServer = 'smtp.163.com'

# 發送郵箱的用戶名和授權碼(不是登錄郵箱的密碼)
username = '[email protected]'
password = 'xxxx'

mail_title = 'xxxxxx'  # 郵件主題
mail_body = 'xxxxxxxx'  # 郵件內容

msg_to = ['xxxxx,xxxxx']#收件人

# 創建一個實例
message = MIMEText(mail_body, 'plain', 'utf-8')  # 郵件正文
message['From'] = sender  # 郵件上顯示的發件人
message['To'] = ','.join(msg_to)  # 郵件上顯示的收件人
message['Subject'] = Header(mail_title, 'utf-8')  # 郵件主題

try:
    smtp = smtplib.SMTP()  # 創建一個連接
    smtp.connect(smtpServer)  # 連接發送郵件的服務器
    smtp.login(username, password)  # 登錄服務器
    smtp.sendmail(sender, message['To'].split(','), message.as_string())  # 填入郵件的相關信息併發送
    print("郵件發送成功!!!")
    smtp.quit()
except smtplib.SMTPException:
    print("郵件發送失敗")

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