smtplib模块发送邮件

import smtplib
from email.mime.text import MIMEText

msg_from = '306334678@qq.com'  # 发送方邮箱
passwd = '****'  # 填入发送方邮箱的授权码(填入自己的授权码,相当于邮箱密码)
msg_to = ['****@qq.com','**@163.com','*****@163.com']  # 收件人邮箱

subject = "邮件标题"  # 主题
content = "邮件内容,我是邮件内容,哈哈哈"
# 生成一个MIMEText对象(还有一些其它参数)
# _text_:邮件内容
msg = MIMEText(content)
# 放入邮件主题
msg['Subject'] = subject
# 也可以这样传参
# msg['Subject'] = Header(subject, 'utf-8')
# 放入发件人
msg['From'] = msg_from
# 放入收件人
msg['To'] = '616564099@qq.com'
# msg['To'] = '发给你的邮件啊'
try:
    # 通过ssl方式发送,服务器地址,端口
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    # 登录到邮箱
    s.login(msg_from, passwd)
    # 发送邮件:发送方,收件方,要发送的消息
    s.sendmail(msg_from, msg_to, msg.as_string())
    print('成功')
except s.SMTPException as e:
    print(e)
finally:
    s.quit()
import smtplib
from email.mime.text import MIMEText

mail_host = "smtp.example.com"
port_ = 465
account = "youraccount@example.com"
password = "password"
receivers = ["receiver@example.com"]

message = MIMEText('This is the body of the email.')
message['Subject'] = 'Subject of the Email'
message['From'] = account
message['To'] = ", ".join(receivers)

try:
    smtp_ = smtplib.SMTP_SSL(mail_host, port=port_)
    smtp_.login(user=account, password=password)
    smtp_.sendmail(account, receivers, message.as_string())
except smtplib.SMTPServerDisconnected as e:
    print(f"Server unexpectedly disconnected: {e}")
except smtplib.SMTPException as e:
    print(f"An SMTP error occurred: {e}")
finally:
    smtp_.quit()
posted @ 2023-04-24 10:45  春游去动物园  阅读(15)  评论(0编辑  收藏  举报