Python发送包含PDF附件的邮件,使用email.mime.application模块
发布时间:2024-01-02 02:01:04
发送包含PDF附件的邮件是利用Python中的email模块实现的,其中使用email.mime.application模块来创建一个带有附件的邮件。
首先,需要导入相关的模块和类:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication
然后,需要设置邮件的相关信息,包括发件人、收件人、主题等等:
sender = 'sender@example.com' receiver = 'receiver@example.com' subject = 'Email with PDF attachment'
接下来,创建一个带有附件的邮件:
msg = MIMEMultipart() msg['From'] = sender msg['To'] = receiver msg['Subject'] = subject
然后,创建邮件的正文,并将其添加到邮件对象中:
body = 'This email contains a PDF attachment.' msg.attach(MIMEText(body, 'plain'))
接下来,打开PDF文件,并将其读取为二进制数据:
with open('example.pdf', 'rb') as f:
pdf_data = f.read()
然后,创建附件对象,并将PDF数据添加到附件对象中:
pdf_attachment = MIMEApplication(pdf_data, Name='example.pdf') pdf_attachment['Content-Disposition'] = 'attachment; filename="example.pdf"' msg.attach(pdf_attachment)
最后,使用SMTP服务器发送邮件:
smtp_server = 'smtp.example.com' username = 'username' password = 'password' server = smtplib.SMTP(smtp_server, 587) server.starttls() server.login(username, password) server.send_message(msg) server.quit()
完整的示例代码如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = 'Email with PDF attachment'
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
body = 'This email contains a PDF attachment.'
msg.attach(MIMEText(body, 'plain'))
with open('example.pdf', 'rb') as f:
pdf_data = f.read()
pdf_attachment = MIMEApplication(pdf_data, Name='example.pdf')
pdf_attachment['Content-Disposition'] = 'attachment; filename="example.pdf"'
msg.attach(pdf_attachment)
smtp_server = 'smtp.example.com'
username = 'username'
password = 'password'
server = smtplib.SMTP(smtp_server, 587)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()
注意:在实际使用中,需要将发件人、收件人、SMTP服务器、用户名和密码等信息替换为真实的信息。
