您需要使用Python编写脚本来完成此任务。以下是示例代码:
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
def send_email(email, password, to, subject, body, attachment_path):
# 创建MIMEMultipart对象并设置邮件头信息
message = MIMEMultipart()
message['From'] = email
message['To'] = to
message['Subject'] = subject
# 添加邮件正文
body_text = MIMEText(body)
message.attach(body_text)
# 添加附件
with open(attachment_path, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_path))
message.attach(attachment)
# 发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = message.as_string()
server.sendmail(email, to, text)
server.quit()
# 设置发送邮件的参数
email = 'example@gmail.com'
password = 'mypassword'
to = 'receiver@example.com'
subject = 'PDF file'
body = 'Please find the attached PDF file.'
attachment_path = 'path/to/myfile.pdf'
# 调用send_email函数并发送邮件
send_email(email, password, to, subject, body, attachment_path)
此代码将创建一个MIMEMultipart对象,并添加正文和附件。当添加附件时,代码使用MIMEApplication对象将文件添加到邮件中。此方法还包括使用smtplib库连接到SMTP服务器。在这种情况下,我们连接到Gmail的SMTP服务器。最后,我们调用sendmail方法将电子邮件发送到收件人的电子邮件地址。