### 示例代码(使用 `smtplib` 和 `email` 模块发送邮件):
“`python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 生成标题和文章内容
def generate_article():
title = “Python 自动化办公的魅力”
content = “””
在当今快节奏的工作环境中,自动化办公工具已经成为提高效率的重要手段。
Python 凭借其简洁的语法和强大的第三方库,成为自动化办公的理想选择。
本文介绍了如何使用 Python 自动生成文章内容并发送邮件,帮助你节省时间,提升效率。
关键点包括:
– 使用 Python 生成结构化文章
– 使用 smtplib 和 email 模块发送邮件
– 自动化邮件正文内容生成
希望这篇文章对你有所帮助!
“””
return title, content
# 发送邮件函数
def send_email(subject, body, sender, receiver, password):
# 创建邮件对象
message = MIMEText(body, ‘plain’, ‘utf-8’)
message[‘From’] = Header(sender)
message[‘To’] = Header(receiver)
message[‘Subject’] = Header(subject)
# 发送邮件
try:
smtp_server = smtplib.SMTP(‘smtp.gmail.com’, 587) # Gmail SMTP 服务器
smtp_server.starttls() # 启用 TLS 加密
smtp_server.login(sender, password)
smtp_server.sendmail(sender, [receiver], message.as_string())
print(“邮件发送成功!”)
except Exception as e:
print(f”邮件发送失败: {e}”)
finally:
smtp_server.quit()
# 主程序
if __name__ == “__main__”:
sender_email = “your_email@gmail.com” # 发件人邮箱
sender_password = “your_app_password” # 应用专用密码(Gmail 需要)
receiver_email = “receiver_email@example.com” # 收件人邮箱
title, article = generate_article()
send_email(title, article, sender_email, receiver_email, sender_password)
“`
—
### 注意事项:
1. **发件人邮箱**:如果你使用的是 Gmail,你需要开启两步验证并生成一个“应用专用密码”。
2. **SMTP 服务器**:不同的邮箱服务提供商有不同的 SMTP 地址和端口。例如:
– Gmail: `smtp.gmail.com`, 端口 `587`
– QQ 邮箱: `smtp.qq.com`, 端口 `587`
3. **加密方式**:大多数邮箱都推荐使用 `TLS` 加密(`starttls()` 方法)。
—
### 如果你只需要生成文章和标题而不发送邮件:
“`python
def generate_article():
title = “Python 自动化办公的魅力”
content = “””
在当今快节奏的工作环境中,自动化办公工具已经成为提高效率的重要手段。
Python 凭借其简洁的语法和强大的第三方库,成为自动化办公的理想选择。
本文介绍了如何使用 Python 自动生成文章内容并发送邮件,帮助你节省时间,提升效率。
关键点包括:
– 使用 Python 生成结构化文章
– 使用 smtplib 和 email 模块发送邮件
– 自动化邮件正文内容生成
希望这篇文章对你有所帮助!
“””
return title, content
title, article = generate_article()
print(“标题:”, title)
print(“\n正文内容:\n”, article)
“`