我撰寫了一個創建 PDF 的代碼,我想用基于 SMTPLIB 庫的 python 代碼將它與另一個檔案(仍然是 .pdf)一起發送。您可以看到str(names[i])接收者電子郵件的值,因為它是從表中獲取的,并且發送程序也使用 for 回圈進行管理,如果剛剛創建的 pdf 的名稱取決于str(names[i])值。
我正在嘗試管理以下代碼,考慮到兩因素身份驗證,以便通過 python 從基于 gmail 的電子郵件發送自動電子郵件:
sender_email = "[email protected]"
receiver_email = str(names[i])
password = input("Authentication code: ")
subject = "Title"
body = """Hi,
This is the body of the email
"""
attachments = ['file1' str(names[i]) '.pdf', 'file2.pdf'] # list of attachments
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email # For mass emails
# Add body to email
message.attach(MIMEText(body, "plain"))
if 'attachments' in globals() and len('attachments') > 0:
for filename in attachments:
f = filename
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
message.attach(part)
# Add header as key/value pair to attachment part
part.add_header("Content-Disposition",f"attachment; filename= {attachments}",)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
一切正常:創建 PDF,發送和接收郵件,但是......附件在非 gmail 電子郵件中不正常。
我在 Outlook 郵件的附件串列中找到的是名為 的檔案(沒有擴展名)['file1' str(names[i]) '.pdf', 'file2.pdf'],并且嘗試使用不同的接收者會得到相同的結果。
似乎非gmail服務器沒有以正確的方式加載檔案,而gmail服務器識別整個程序
我想過在最后一個with條件下寫一個“多服務器”物件,但我不知道該怎么做。
謝謝你們!
uj5u.com熱心網友回復:
在簡化的代碼中,您可以這樣做:
# block#1 The following is simplified ---
for filename in attachments:
part = ... # construct part, include file content
part.add_header('Content-Disposition', ...)
message.attach(part)
# block#2: The following is original code ----
# Add header as key/value pair to attachment part
part.add_header("Content-Disposition",f"attachment; filename= {attachments}",)
# Add attachment to message and convert message to string
message.attach(part)
因此,你
- 在 block#1 中,您首先為每個檔案創建一個部分
- 然后在 block#2 中,從 block#1 中取出最后一部分并添加另一個 content-disposition 標頭,其中包括名稱串列作為名稱
- 然后在塊#2 中再次將此部分附加到此訊息
顯然,block#1 是你所需要的,而 block#2 只是把一切都搞砸了。去掉它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515876.html
