使用Python从文件夹以电子邮件形式发送随机的PDF文件可以通过以下步骤实现:
import os
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
sender_email = "your_email@example.com"
sender_password = "your_email_password"
receiver_email = "recipient_email@example.com"
def get_random_pdf(folder_path):
pdf_files = [file for file in os.listdir(folder_path) if file.endswith(".pdf")]
random_pdf = random.choice(pdf_files)
return random_pdf
def send_email_with_pdf(sender_email, sender_password, receiver_email, pdf_file):
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Random PDF File"
body = "Please find the attached random PDF file."
msg.attach(MIMEText(body, "plain"))
with open(pdf_file, "rb") as file:
attachment = MIMEApplication(file.read(), _subtype="pdf")
attachment.add_header("Content-Disposition", "attachment", filename=pdf_file)
msg.attach(attachment)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
folder_path = "/path/to/pdf/folder"
random_pdf_file = get_random_pdf(folder_path)
send_email_with_pdf(sender_email, sender_password, receiver_email, random_pdf_file)
这样,Python将会从指定文件夹中选择一个随机的PDF文件,并将其作为附件发送到指定的收件人邮箱中。
请注意,以上代码示例中的发件人邮箱需要是支持SMTP服务的邮箱,如Gmail。你需要将your_email@example.com
和your_email_password
替换为你自己的发件人邮箱和密码。同时,将recipient_email@example.com
替换为接收者的邮箱地址。
对于腾讯云相关产品和产品介绍链接地址,由于要求不能提及具体的云计算品牌商,因此无法提供相关链接。但你可以根据自己的需求选择适合的云计算服务提供商,并查阅其文档以了解如何在其平台上实现相应的功能。
领取专属 10元无门槛券
手把手带您无忧上云