【问题标题】:How can I attach all images file in directory using MIME如何使用 MIME 附加目录中的所有图像文件
【发布时间】:2021-06-16 12:03:36
【问题描述】:
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import os

project_name = "ถังเก็บน้ำดับเพลิง 350m3 บีพี"
notwearing = 5
output_paths ='/Users/khemakorn/Downloads/export_files/pk98_ปรับปรุงฝ้าและผนังโรงอาหาร โรงชำแหละสุกร พนมทวน กาญจนบุรี'


do_not_reply ="****DO NOT REPLY THIS EMAIL****"
# messages = project_name+" "+str(notwearing)+" ครั้ง\n\n\n"
mail_content = """ตรวจพบผู้ไม่สวมหมวกนิรภัยในโครงการ """+project_name+""" จำนวน """+str(notwearing)+""" ครั้ง \n\n\n\n"""+do_not_reply
#The mail addresses and password
sender_address = 'xxxxxx@gmail.com'
sender_pass = 'xxxxx'
receiver_address = ['xxxxxxx@mail.xxxx.ac.th','xxxxxx@icloud.com']
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = ','.join(receiver_address)
message['Subject'] = 'TESTTEST'   #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
fp = open('k.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
# msgImage.add_header('Content-ID', '<image2>')
message.attach(msgImage2)
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

现在只能发送代码同目录下的图片了 但我希望它发送'output_paths'中的所有图像文件我该怎么做。 我确实尝试了一些 for 循环作为互联网上的示例,但它甚至无法运行

【问题讨论】:

    标签: python image email mime-types mime


    【解决方案1】:
    sending_path = glob.glob(output_paths+"/*")
    random.shuffle(sending_path)
    for img_path in sending_path:
    
        fp = open(img_path, 'rb')
        msgImage2 = MIMEImage(fp.read())
        message.attach(msgImage2)
    

    完成

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2014-08-26
      • 2023-03-28
      • 2012-09-02
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      相关资源
      最近更新 更多