Python 发邮件

内容来自文心一言

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

# 设置发件人、收件人、主题和正文
sender = ‘your_email_address’
recipient = ‘recipient_email_address’
subject = ‘邮件主题’
body = ‘邮件正文’

# 创建邮件对象
message = MIMEMultipart()
message[‘From’] = sender
message[‘To’] = recipient
message[‘Subject’] = subject

# 添加邮件正文
text = MIMEText(body)
message.attach(text)

# 添加附件
filename = ‘attachment_file_name.txt’
with open(filename, ‘rb’) as f:
attachment = MIMEApplication(f.read(), _subtype=’txt’)
attachment.add_header(‘Content-Disposition’, ‘attachment’, filename=filename)
message.attach(attachment)

# 发送邮件
try:
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(sender, ‘password’)
server.sendmail(sender, recipient, message.as_string())
print(‘邮件发送成功’)
except Exception as e:
print(‘邮件发送失败’)
print(e)
finally:
server.quit()

You may also like...

发表回复