代码
import smtplib
import socket
from email.mime.text import MIMEText
from email.header import Header
def send_mail():
# 设置发件人、收件人、主题、内容
from_address = '18847097110@163.com'
to_address = '963268595@qq.com'
subject = 'test email'
body = 'hahahhahaha'
# SMTP邮件服务器
smtp_server = 'smtp.163.com'
smtp_port = 25
# 发件人账号和密码
username = '18847097110@163.com'
password = 'your password'
# 创建邮件内容
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = Header(subject, 'utf-8')
server = None # 初始化 server
try:
# 检查端口是否通畅
sock = socket.create_connection((smtp_server, smtp_port), timeout=5)
sock.close()
# 连接邮件服务器并发送邮件
server = smtplib.SMTP(smtp_server, smtp_port)
server.login(username, password)
server.sendmail(from_address, to_address, msg.as_string())
print('Email send successfully!')
#捕获socket的error
except socket.error as e:
print('Socket error occurred:', e)
#捕获smtplib的error
except smtplib.SMTPException as e:
print('SMTP error occurred:', e)
#捕获任何类型的异常
except Exception as e:
print('An error occurred:', e)
#无论是否发生异常,此模块下的代码都会执行
finally:
if server is not None:
server.quit()
if __name__ == '__main__':
send_mail()
返回
捕获异常
将端口修改成一个错误的端口,会提示报错 连接端口失败
填写一个错误的账号或者是密码,会提示认证失败