Hướng dẫn attach multiple files to email python - đính kèm nhiều tệp vào email python

Tôi có mã sau để gửi tệp HTML SeleniumTestreport_Part1.html trong một email trong Python. Tôi muốn gửi nhiều hơn 1 tệp trong email. Làm thế nào để tôi có thể làm điều này?

Các tệp tôi muốn gửi là: seleniumtestreport_part1.html seleniumtestreport_part2.html seleniumtestreport_part3.html
SeleniumTestReport_part3.html

Mã của tôi để gửi 1 tệp là:

def send_selenium_report[]:
    fileToSend = r"G:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html"
    with open[fileToSend, "rt"] as f:
        text = f.read[]
    msg = MIMEText[text, "html"]
    msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"
    msg['to'] = ""
    msg['From'] = ""

    s = smtplib.SMTP[]
    s.connect[host=SMTP_SERVER]
    s.sendmail[msg['From'], msg['To'], msg.as_string[]]
    s.close[]

Cảm ơn, Riaz

Vzzarr

4.0001 Huy hiệu vàng36 Huy hiệu bạc64 Huy hiệu đồng1 gold badge36 silver badges64 bronze badges

Khi được hỏi ngày 13 tháng 5 năm 2016 lúc 8:26May 13, 2016 at 8:26

Riaz Ladhaniriaz LadhaniRiaz Ladhani

3,80615 Huy hiệu vàng68 Huy hiệu bạc123 Huy hiệu đồng15 gold badges68 silver badges123 bronze badges

3

Nếu bạn muốn đính kèm các tệp vào email, bạn có thể chỉ sử dụng lặp lại các tệp và đính kèm chúng vào tin nhắn. Bạn cũng có thể muốn thêm một số văn bản vào cơ thể. Đây là mã:

import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_selenium_report[]:
    dir_path = "G:/test_runners/selenium_regression_test_5_1_1/TestReport"
    files = ["SeleniumTestReport_part1.html", "SeleniumTestReport_part2.html", "SeleniumTestReport_part3.html"]

    msg = MIMEMultipart[]
    msg['To'] = ""
    msg['From'] = ""
    msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"

    body = MIMEText['Test results attached.', 'html', 'utf-8']  
    msg.attach[body]  # add message body [text or html]

    for f in files:  # add files to the message
        file_path = os.path.join[dir_path, f]
        attachment = MIMEApplication[open[file_path, "rb"].read[], _subtype="txt"]
        attachment.add_header['Content-Disposition','attachment', filename=f]
        msg.attach[attachment]

    s = smtplib.SMTP[]
    s.connect[host=SMTP_SERVER]
    s.sendmail[msg['From'], msg['To'], msg.as_string[]]
    print 'done!'
    s.close[]

Đã trả lời ngày 13 tháng 5 năm 2016 lúc 10:20May 13, 2016 at 10:20

1

Tôi đã thực hiện điều này để gửi thư từ Gmail.

import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders

def send_mail_gmail[username,password,toaddrs_list,msg_text,fromaddr=None,subject="Test mail",attachment_path_list=None]:

    s = smtplib.SMTP['smtp.gmail.com:587']
    s.starttls[]
    s.login[username, password]
    #s.set_debuglevel[1]
    msg = MIMEMultipart[]
    sender = fromaddr
    recipients = toaddrs_list
    msg['Subject'] = subject
    if fromaddr is not None:
        msg['From'] = sender
    msg['To'] = ", ".join[recipients]
    if attachment_path_list is not None:
        for each_file_path in attachment_path_list:
            try:
                file_name=each_file_path.split["/"][-1]
                part = MIMEBase['application', "octet-stream"]
                part.set_payload[open[each_file_path, "rb"].read[]]

                Encoders.encode_base64[part]
                part.add_header['Content-Disposition', 'attachment' ,filename=file_name]
                msg.attach[part]
            except:
                print "could not attache file"
    msg.attach[MIMEText[msg_text,'html']]
    s.sendmail[sender, recipients, msg.as_string[]]

Bạn có thể chuyển nhiều địa chỉ dưới dạng yếu tố của toaddrs_list mà bạn muốn gửi thư và nhiều tên tệp đính kèm với đường dẫn của họ trong attachment_path_list.

Đã trả lời ngày 13 tháng 5 năm 2016 lúc 10:55May 13, 2016 at 10:55

TanutanuTanu

1.44312 huy hiệu bạc21 Huy hiệu đồng12 silver badges21 bronze badges

user = 'user_name'# email userid

mật khẩu = 'xxxxxxxxx'# mật khẩu email
người nhận_addr = ['', '', '']]
"" "
Chủ đề = 'Kiểm tra thư smtp'
Body = 'Xin chào từ SMTP'
file_path = ['/path/file.txt', 'Image.png', '/path/clip.mp4']]
send_email [người dùng, mật khẩu, từ_addr, người nhận_addr, chủ đề, body, file_path]
Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây. Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn. Tìm hiểu thêm về các ký tự unicode hai chiều
#!/usr/bin/env Python
"" "
#-*-Mã hóa: UTF-8-*- os
Kịch bản này được thiết kế để gửi email đến nhiều người tiếp tân từ các máy chủ SMTP cục bộ và các máy chủ SMTP khác. smtplib
Bất kỳ loại tài liệu nào cũng có thể được đính kèm với email sẽ được gửi. mimetypes
Để gửi email từ máy chủ SMTP cục bộ, người ta cho rằng ứng dụng email đã email import encoders
fromemail.mime.multipartimportMIMEMultipart email.mime.multipart import MIMEMultipart
fromemail.mime.textimportMIMEText email.mime.text import MIMEText
fromemail.mime.baseimportMIMEBase email.mime.base import MIMEBase
__author__='haccks' = 'haccks'
Được cấu hình trên hệ thống địa phương của bạn [Postfix, SendMail, v.v.]. = 'Oct 16 2018'
Để gửi email từ máy chủ Gmail, cần phải cho phép "các ứng dụng ít an toàn hơn" mime_init[from_addr, recipients_addr, subject, body]:
"" "
: param str from_addr: địa chỉ email bạn muốn gửi thư từ
[//myaccount.google.com/lessSecureApps] trong tài khoản Google của bạn
: param str chủ đề: chủ đề thư
: param str body: cơ thể thư
: param List Files_path: Danh sách các đường dẫn của các tệp bạn muốn đính kèm
"" "
# Assert isInstance [người nhận_addr, danh sách] = MIMEMultipart[]
To = recker_addrifisInstance [người nhận_addr, danh sách] elserecipents_addr.split ['' ']['From'] = from_addr
MSG = mime_init [từ, đến, chủ đề, cơ thể]['To'] = ','.join[recipients_addr]
forfile_pathinfiles_pathor []:['Subject'] = subject
withopen [file_path, "rb"] ASFP:.attach[MIMEText[body, 'plain']]
part = mimebase ['application', "octet-stream"] msg
part.set_payload [[fp] .read []] send_email[user, password, from_addr, recipients_addr, subject, body, files_path=None, server='smtp.gmail.com']:
"" "
: param str người dùng: userid email của người gửi
: PARAM STR Mật khẩu: Mật khẩu email của người gửi
: param str from_addr: địa chỉ email bạn muốn gửi thư từ
: Danh sách tham số Người nhận_addr: Danh sách [hoặc chuỗi phân tách không gian] Địa chỉ email của người nhận
: param str chủ đề: chủ đề thư
: param str body: cơ thể thư
: param List Files_path: Danh sách các đường dẫn của các tệp bạn muốn đính kèm
: param str Server: SMTP Server [cổng được chọn 587]
: return: không
"" "
# Assert isInstance [người nhận_addr, danh sách]
FROM=from_addr = from_addr
To = recker_addrifisInstance [người nhận_addr, danh sách] elserecipents_addr.split ['' '] = recipients_addr if isinstance[recipients_addr, list] else recipients_addr.split[' ']
PASS=password = password
SERVER=server = server
SUBJECT=subject = subject
BODY=body = body
MSG = mime_init [từ, đến, chủ đề, cơ thể] = mime_init[FROM, TO, SUBJECT, BODY]
forfile_pathinfiles_pathor []: file_path in files_path or []:
withopen [file_path, "rb"] ASFP: open[file_path, "rb"] as fp:
part = mimebase ['application', "octet-stream"] = MIMEBase['application', "octet-stream"]
part.set_payload [[fp] .read []].set_payload[[fp].read[]]
# Tải trọng mã hóa là cần thiết nếu tệp được mã hóa [nén] phải được đính kèm.
bộ mã hóa.encode_base64 [một phần].encode_base64[part]
part.add_header ['nội dung-phân tích', "đính kèm; fileName = %s" %os.path.basename [file_path]].add_header['Content-Disposition', "attachment; filename= %s" % os.path.basename[file_path]]
msg.attach [một phần].attach[part]
ifserver == 'localhost': # Gửi thư từ máy chủ cục bộ SERVER == 'localhost': # send mail from local server
# Khởi động máy chủ SMTP cục bộ
server = smtplib.smtp [máy chủ] = smtplib.SMTP[SERVER]
text = msg.as_string [] = msg.as_string[]
server.send_message [MSG].send_message[msg]
khác::
# Bắt đầu máy chủ SMTP tại cổng 587
server = smtplib.smtp [máy chủ, 587] = smtplib.SMTP[SERVER, 587]
server.starttls [].starttls[]
# Nhập thông tin đăng nhập cho email bạn muốn gửi thư từ
server.login [người dùng, vượt qua].login[user, PASS]
text = msg.as_string [] = msg.as_string[]
# Gửi thư
server.sendmail [từ, đến, văn bản].sendmail[FROM, TO, text]
server.quit [].quit[]
if__name __ == "__ main__": __name__ == "__main__":
user = 'user_name'# email userid = 'USER_NAME' # Email userID
mật khẩu = 'xxxxxxxxx'# mật khẩu email = 'XXXXXXXX' # Email password
from_addr='' = ''
người nhận_addr = ['', '', '']] = ['', '', '']
Chủ đề = 'Kiểm tra thư smtp' = 'SMTP mail test'
Body = 'Xin chào từ SMTP' = 'Hello from SMTP'
file_path = ['/path/file.txt', 'Image.png', '/path/clip.mp4']] = ['/Path/file.txt', 'image.png', '/Path/clip.mp4']
send_email [người dùng, mật khẩu, từ_addr, người nhận_addr, chủ đề, body, file_path][user, password, from_addr, recipients_addr, subject, body, file_path]

Bài Viết Liên Quan

Chủ Đề