在Python中,你可以使用smtplib库来发送电子邮件。以下是一个简单的例子,演示如何使用SMTP发送邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 邮件配置
smtp_server = 'your_smtp_server'
smtp_port = 587  # 使用TLS时的端口号
sender_email = 'your_email@example.com'
sender_password = 'your_email_password'
receiver_email = 'recipient@example.com'

# 创建消息对象
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = 'Test Subject'

# 邮件正文
body = 'This is a test email.'
message.attach(MIMEText(body, 'plain'))

# 配置SMTP连接
with smtplib.SMTP(smtp_server, smtp_port) as server:
    # 开启安全连接
    server.starttls()

    # 登录邮箱
    server.login(sender_email, sender_password)

    # 发送邮件
    server.sendmail(sender_email, receiver_email, message.as_string())

print('邮件发送成功')

请替换以下信息:

  •  your_smtp_server: SMTP服务器地址

  •  smtp_port: SMTP服务器端口号(一般是587,使用TLS时)

  •  your_email@example.com: 发件人邮箱地址

  •  your_email_password: 发件人邮箱密码

  •  recipient@example.com: 收件人邮箱地址


确保在发送邮件之前,你已经开启了邮箱的SMTP服务,并且你提供的邮箱信息是正确的。此外,注意保护敏感信息,如邮箱密码。

这只是一个基本的示例,实际应用中可能需要更多的配置和处理。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13287/Python3