Python中使用MIMEText()发送带附件的邮件的步骤
发布时间:2024-01-03 04:04:09
发送带附件的邮件可以使用Python的smtplib库和email库来实现。下面是使用MIMEText()发送带附件邮件的步骤:
1. 导入所需要的库
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication
2. 创建MIMEMultipart对象,并设置邮件的 Subject、From、To 等信息
msg = MIMEMultipart() msg['Subject'] = 'This is a test email with attachment' msg['From'] = 'sender@example.com' msg['To'] = 'receiver@example.com'
3. 创建邮件正文的MIMEText对象,并将其加入到MIMEMultipart对象中
body = MIMEText('This is the body of the email')
msg.attach(body)
4. 读取附件文件,创建MIMEApplication对象,并将其加入到MIMEMultipart对象中
with open('attachment.txt', 'rb') as f:
attachment = MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.attach(attachment)
5. 连接到SMTP服务器,并发送邮件
smtp_server = "smtp.example.com"
smtp_port = 587
username = "sender@example.com"
password = "password"
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(username, password)
server.send_message(msg)
这就是使用MIMEText()发送带附件邮件的例子。在这个例子中,我们首先创建了一个MIMEMultipart的对象,然后设置了邮件的主题、发件人和收件人等信息。接着,我们创建了邮件正文的MIMEText对象,并将其加入到MIMEMultipart对象中。最后,我们读取了附件文件,创建了一个MIMEApplication对象,并将其加入到MIMEMultipart对象中。最后,我们通过SMTP服务器发送了这个带附件的邮件。
请注意,在使用这个例子时,你需要将 smtp_server、smtp_port、username 和 password 替换成你实际的 SMTP 服务器地址、端口号、用户名和密码。
