欢迎访问宙启技术站
智能推送

Python中使用MIMEBase()发送带PDF附件的邮件步骤

发布时间:2024-01-17 01:33:49

Python中使用MIMEBase()发送带PDF附件的邮件可以分为以下几个步骤:

1. 导入相关的库

首先,我们需要导入emailsmtplib库以及相关的MIME模块,代码如下:

   import smtplib
   from email.mime.text import MIMEText
   from email.mime.multipart import MIMEMultipart
   from email.mime.base import MIMEBase
   from email import encoders
   

2. 创建MIMEMultipart对象

创建一个MIMEMultipart对象来代表邮件的主体部分,代码如下:

   msg = MIMEMultipart()
   

3. 设置邮件的发送者、接收者和主题

使用msg对象的['From']['To']['Subject']属性来设置邮件的发送者、接收者和主题,代码如下:

   msg['From'] = 'sender@example.com'
   msg['To'] = 'recipient@example.com'
   msg['Subject'] = 'Sample email with PDF attachment'
   

4. 添加邮件正文

使用MIMEText()创建邮件正文的实例,并将其添加到msg对象中,代码如下:

   body = 'This is the body of the email'
   msg.attach(MIMEText(body, 'plain'))
   

5. 读取PDF文件内容并添加为附件

首先,使用open()函数读取PDF文件的内容,并用MIMEBase()创建一个表示附件的实例。然后,设置附件的属性,并将其内容附加到邮件中,代码如下:

   filename = 'sample.pdf'
   attachment = open(filename, 'rb')

   part = MIMEBase('application', 'octet-stream')
   part.set_payload((attachment).read())
   encoders.encode_base64(part)
   part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

   msg.attach(part)
   

6. 将MIMEMultipart对象转换成字符串并发送邮件

最后,将msg对象转换为字符串,并使用SMTP类将邮件发送出去。需要提供邮件服务器的地址和端口,以及发送者的邮箱账号和密码,代码如下:

   server = smtplib.SMTP('smtp.gmail.com', 587)
   server.starttls()
   server.login("sender@example.com", "password")
   text = msg.as_string()
   server.sendmail("sender@example.com", "recipient@example.com", text)
   server.quit()
   

下面是完整的示例代码:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg = MIMEMultipart()

msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Sample email with PDF attachment'

body = 'This is the body of the email'
msg.attach(MIMEText(body, 'plain'))

filename = 'sample.pdf'
attachment = open(filename, 'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("sender@example.com", "password")
text = msg.as_string()
server.sendmail("sender@example.com", "recipient@example.com", text)
server.quit()

以上代码示例使用Gmail的SMTP服务器发送邮件,需要替换'sender@example.com'为发送者的邮箱地址,'recipient@example.com'为接收者的邮箱地址,以及'password'为发送者的邮箱密码。

注意:在使用Gmail SMTP服务器发送邮件之前,需要先在Gmail账号的设置中开启“允许较低安全性的应用访问”。其他SMTP服务器可能有不同的设置要求。