欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python学习(1)--发邮件

程序员文章站 2022-03-18 20:42:36
...
# -*- coding:utf-8 -*-
from email.mime.text import MIMEText
from email.header import Header
import smtplib


message ='''
hello,world!
来自我的电脑
'''

msg = MIMEText(message,'plain','utf-8')

msg['Subject'] = Header("来自Python的邮件",'utf-8')
msg['From'] = Header('***@sina.com')
msg['To'] = Header('receiver','utf-8')

from_addr = '****@sina.com' #发件邮箱
password = '****' #邮箱密码
to_addr = '****@163.com' #收件邮箱

smtp_server = 'smtp.sina.com' #SMTP服务器


try:
    server = smtplib.SMTP(smtp_server,25) #第二个参数为默认端口为25,有些邮件有特殊端口
    print('开始登录')
    server.login(from_addr,password) #登录邮箱
    print('登录成功')
    print("邮件开始发送")
    server.sendmail(from_addr,to_addr,msg.as_string())  #将msg转化成string发出
    server.quit()
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("邮件发送失败",e)