以下是Python发送邮件的示例代码:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发件人和收件人邮箱地址
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
# 邮件主题和内容
subject = 'Test Email'
content = 'This is a test email sent from Python.'
# 创建MIMEText对象,设置邮件内容和编码格式
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header('Your Name', 'utf-8') # 发件人名称
message['To'] = Header('Recipient Name', 'utf-8') # 收件人名称
message['Subject'] = Header(subject, 'utf-8') # 邮件主题
# 登录SMTP服务器并发送邮件
try:
smtpObj = smtplib.SMTP('smtp.example.com', 25) # 根据实际情况填写SMTP服务器地址和端口号
smtpObj.login('your_email@example.com', 'your_password') # 填写发件人邮箱地址和密码
smtpObj.sendmail(sender, [receiver], message.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("Error: 无法发送邮件", e)
请将代码中的your_email@example.com
、recipient_email@example.com
、smtp.example.com
、your_password
等参数替换为实际的值。