Python写邮件发送代码示例
## 导入必要的库
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
## 设置发件人和收件人邮箱
sender_email = "your_email@example.com"
recipient_email = "recipient@example.com"
## 邮件内容
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = "这是一封测试邮件"
body = "这是一封测试邮件,发送自树莓派"
msg.attach(MIMEText(body, 'plain'))
## 添加附件(可选)
with open('/home/pi/Desktop/2022Study/wifi.txt', 'rb') as f:
att = MIMEApplication(f.read(), _subtype='octet-stream')
att.add_header('Content-Disposition', 'attachment', filename='att.txt')
msg.attach(att)
## 发送邮件
smtp_server = "smtp.example.com" # 发件人邮箱所属SMTP服务器地址
smtp_port = 587 # SMTP服务端口
smtp_username = "your_email@example.com" # 发件人邮箱账号
smtp_password = "smtp授权码" # 发件人邮箱SMTP授权码
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
server.quit()
下载地址
用户评论
这个文件的步骤详细清晰,让我在不同的环境下都能够成功运行,非常实用。
这个文件详细解释了如何使用Python在树莓派上进行邮件发送,让人觉得操作简单易懂。
通过这个文件,我学到了如何使用Python库来实现邮件发送,很方便实用。