如何使用Python发送带附件的文本电子邮件(使用email.mime.text)
发布时间:2023-12-23 09:54:49
发送带附件的文本电子邮件可以使用Python的标准库email和email.mime.text。email.mime.text用于创建包含文本内容的邮件对象,并设置附件。下面是一个使用Python发送带附件的文本电子邮件的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 创建邮件对象
msg = MIMEMultipart()
# 添加发件人、收件人、主题信息
msg['From'] = 'sender@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = '邮件主题'
# 添加邮件正文
body = MIMEText('这是邮件的正文内容。')
msg.attach(body)
# 添加附件
filename = '附件.txt'
attachment = MIMEText(open(filename, 'rb').read(), 'plain')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'sender@example.com'
password = 'password'
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print('邮件发送成功')
except Exception as e:
print('邮件发送失败:', str(e))
上述代码首先导入了所需的库,然后创建了一个MIMEMultipart邮件对象。然后,设置了发件人、收件人和邮件主题等信息,并添加了邮件正文。接下来,从本地文件中读取附件的内容,并将其添加到邮件对象中作为附件。最后,通过SMTP服务器发送了该邮件。
请注意,上述代码中的smtp_server、smtp_port、username和password等变量需要根据实际情况进行修改。
以上是一个简单的使用例子,可以根据自己的需求进行修改和扩展。
