使用Python的smtplib模块发送邮件的步骤是什么
发布时间:2024-01-16 04:06:37
使用Python的smtplib模块发送邮件的步骤如下:
1. 导入smtplib模块和email模块:
import smtplib from email.mime.text import MIMEText
2. 创建MIMEText对象,并设置邮件内容、发件人、收件人等信息:
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
msg['Subject'] = '邮件主题'
3. 使用SMTP服务器登录发件人邮箱:
smtp_server = 'SMTP服务器地址'
smtp_port = 25 # SMTP服务器端口
sender_email = '发件人邮箱'
sender_password = '发件人邮箱密码'
try:
smtpObj = smtplib.SMTP(smtp_server, smtp_port)
smtpObj.login(sender_email, sender_password)
except Exception as e:
print('登录失败:', e)
exit()
4. 发送邮件:
try:
smtpObj.sendmail(sender_email, [msg['To']], msg.as_string())
print('邮件发送成功!')
except smtplib.SMTPException:
print('邮件发送失败!')
finally:
smtpObj.quit()
下面是一个完整的发送邮件的例子:
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('这是一封使用Python发送的测试邮件', 'plain', 'utf-8')
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = '测试邮件'
smtp_server = 'smtp.example.com'
smtp_port = 25
sender_email = 'sender@example.com'
sender_password = 'password'
try:
smtpObj = smtplib.SMTP(smtp_server, smtp_port)
smtpObj.login(sender_email, sender_password)
except Exception as e:
print('登录失败:', e)
exit()
try:
smtpObj.sendmail(sender_email, [msg['To']], msg.as_string())
print('邮件发送成功!')
except smtplib.SMTPException:
print('邮件发送失败!')
finally:
smtpObj.quit()
这是一个简单的使用Python的smtplib模块发送邮件的例子。在实际使用中,你可能还需要添加异常处理、附件发送等功能,以满足具体需求。
