python发送邮件代码

moonjerx
2024-05-10 / 0 评论 / 42 阅读 / 正在检测是否收录...
import ssl
import smtplib
from email.utils import formataddr
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(to_user, subject, content):
    # 创建一个MIMEMultipart对象,用于组合邮件头部和正文
    mail_username='notify@example.com'
    mail_password='xxxxxxxxxx'
    smtp_server = "smtp.test.com"
    message = MIMEMultipart()
    message['From'] = formataddr(pair=('MX-Notify', mail_username))
    message['To'] = to_user
    message['Subject'] = Header(subject, 'utf-8')  # 标题

    # 创建邮件正文
    # text = f"""
    # {content}
    # It can be in HTML or plain text.
    # """
    html = f"""
    <html>
    <body>
        <p>{content}</p>
    </body>
    </html>
    """
    # 添加正文到邮件对象中
    # message.attach(MIMEText(text, "plain"))
    message.attach(MIMEText(html, "html"))

    # 添加邮件正文

    # 设置SMTP服务器和端口
    smtp_server = smtp_server
    port = 465  # 假设使用的是SSL,如果是TLS,通常使用587
    server = None  # 先初始化为None
    try:
        # 创建SMTP SSL连接
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        server = smtplib.SMTP_SSL(smtp_server, port, context=context)

        # 非SSL,如果为SSL则看下面
        # server = smtplib.SMTP(smtp_server)

        # 如果是ssl,需要加多一个端口号映射
        # server = smtplib.SMTP_SSL()
        # server.connect(smtp_server,port,context)

        # 登录邮箱
        server.login(mail_username, mail_password)

        # 发送邮件
        server.sendmail(mail_username, recipient, message.as_string())

        print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败:{e}")
    finally:
        # 关闭SMTP连接
        if server is not None:
            server.quit()

# 使用示例
try:
    has_msg = check_fun(check_url)
    send_email("touser@qq.com", '检测PT开注', "这是一封测试邮件。")
except Exception as e:
    print(f"发生错误:{e}")
0

评论 (0)

取消

您的IP: