前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Send Email by Python

Send Email by Python

作者头像
alanzeng
发布2025-01-14 21:46:01
发布2025-01-14 21:46:01
7700
代码可运行
举报
文章被收录于专栏:alanzeng423alanzeng423
运行总次数:0
代码可运行

使用Python发送邮件

Key_points:

SMTP服务器地址和端口

使用TLS加密: 587

代码语言:javascript
代码运行次数:0
复制
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()

使用SSL加密: 465

代码语言:javascript
代码运行次数:0
复制
server = smtplib.SMTP_SSL(smtp_server, smtp_port)

代码如下:

代码语言:javascript
代码运行次数:0
复制
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 发送邮件
def send_email():
    print("Preparing to send email...")
    sender_email = 'your_email@example.com'
    receiver_email = 'receiver_email@example.com'
    password = 'your_email_password'

    smtp_server = 'smtp.yourmail.com'
    smtp_port = 587 # SMTP端口, 通常为587(TSL)或465(SSL)

    subject = 'subject'
    body = 'body'

    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject
    message.attach(MIMEText(body, 'plain'))

    try:
        print("Connecting to SMTP server...")
        # If you want to use SSL, use `smtplib.SMTP_SSL()` instead and remove `server.starttls()`
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()  # 使用TLS加密
            print("Logging in to SMTP server...")
            server.login(sender_email, password)  # 登录
            print("Sending email...")
            server.sendmail(sender_email, receiver_email, message.as_string())  # 发送邮件
            print("Email sent successfully.")
    except Exception as e:
        print(f"Email sent failed: {e}")

# 主函数
def main():
    send_mail()

文章作者: Alan Zeng

原始链接: https://alanzeng.com/blogs/1299/

版权说明:本博客所有文章除特别声明外,均采用BY-NC-SA 4.0许可协议。获得许可后,要求转载时注明文章出处和网站链接,谢谢!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档