📜  如何在Python自动发送电子邮件(1)

📅  最后修改于: 2023-12-03 15:38:37.459000             🧑  作者: Mango

如何在Python自动发送电子邮件

如果您想在Python中自动发送电子邮件,那么您可以使用Python的内置模块 - smtplib

步骤

以下是一个基本的步骤来在Python中自动发送电子邮件:

  1. 导入必要的模块:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
  1. 定义SMTP服务器和端口号:
smtp_server = 'smtp.gmail.com'  # 以Gmail为例
smtp_port = 587
  1. 创建SMTP服务器连接:
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
  1. 登录您的账户:
username = 'your_email_address@gmail.com'  # 用您自己的邮件地址替换
password = 'your_email_password'  # 用您的邮箱密码替换
smtp_conn.login(username, password)
  1. 创建电子邮件:
msg = MIMEMultipart()
msg['From'] = 'your_email_address@gmail.com'
msg['To'] = 'recipient_email_address@mail.com'
msg['Subject'] = 'Test email from Python'

body = 'Hello, this is a test email from Python!'
msg.attach(MIMEText(body, 'plain'))
  1. 发送电子邮件:
smtp_conn.sendmail(username, 'recipient_email_address@mail.com', msg.as_string())
  1. 关闭SMTP服务器连接:
smtp_conn.quit()
完整代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

smtp_server = 'smtp.gmail.com'
smtp_port = 587

smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()

username = 'your_email_address@gmail.com'
password = 'your_email_password'
smtp_conn.login(username, password)

msg = MIMEMultipart()
msg['From'] = 'your_email_address@gmail.com'
msg['To'] = 'recipient_email_address@mail.com'
msg['Subject'] = 'Test email from Python'

body = 'Hello, this is a test email from Python!'
msg.attach(MIMEText(body, 'plain'))

smtp_conn.sendmail(username, 'recipient_email_address@mail.com', msg.as_string())
smtp_conn.quit()

以上便是在Python中自动发送电子邮件的基本步骤,您可以根据您的需求进行修改。