使用Python的smtplib库发送邮件的步骤详解
发布时间:2023-12-25 13:21:47
使用Python的smtplib库发送邮件的步骤详解:
1. 导入相应的模块和库:
import smtplib from email.mime.text import MIMEText
2. 配置邮件信息,包括发件人、收件人、主题和正文:
sender = 'test@example.com' receiver = 'admin@example.com' subject = 'Example Subject' body = 'This is the body of the email.'
3. 创建MIMEText对象,设置邮件内容为纯文本:
msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver
4. 连接到SMTP服务器,并登录:
smtp_server = 'smtp.example.com' smtp_user = 'username' smtp_password = 'password' smtp_obj = smtplib.SMTP(smtp_server, 587) smtp_obj.starttls() smtp_obj.login(smtp_user, smtp_password)
注意,需要根据自己的情况替换为对应的SMTP服务器地址、登录用户名和密码。
5. 发送邮件:
smtp_obj.sendmail(sender, receiver, msg.as_string())
6. 关闭连接:
smtp_obj.quit()
下面是一个完整的例子,发送一个包含HTML内容的邮件:
import smtplib from email.mime.text import MIMEText sender = 'test@example.com' receiver = 'admin@example.com' subject = 'Example Subject' body = '<h1>This is the body of the email.</h1>' msg = MIMEText(body, 'html') msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver smtp_server = 'smtp.example.com' smtp_user = 'username' smtp_password = 'password' smtp_obj = smtplib.SMTP(smtp_server, 587) smtp_obj.starttls() smtp_obj.login(smtp_user, smtp_password) smtp_obj.sendmail(sender, receiver, msg.as_string()) smtp_obj.quit()
这是一个简单的例子,发送一个包含HTML内容的邮件。可以根据需要对邮件的内容进行进一步的定制化。
