欢迎访问宙启技术站
智能推送

在Python中如何发送电子邮件

发布时间:2023-12-16 11:31:40

在Python中,我们可以使用smtplib模块来发送电子邮件。以下是一个基本的示例,演示如何使用Python发送电子邮件:

import smtplib
from email.mime.text import MIMEText

def send_email(sender_email, sender_password, recipient_email, subject, message):
    # 创建邮件内容
    email_content = MIMEText(message, "plain")
    email_content["Subject"] = subject
    email_content["From"] = sender_email
    email_content["To"] = recipient_email
    
    try:
        # 启动SMTP服务并建立与邮件服务器的连接
        smtp_server = smtplib.SMTP("smtp.gmail.com", 587)  # 使用Gmail的SMTP服务器,端口为587
        smtp_server.starttls()  # 启用TLS加密
        smtp_server.login(sender_email, sender_password)  # 登录到发送邮件的账户
        
        # 发送邮件
        smtp_server.sendmail(sender_email, recipient_email, email_content.as_string())
        print("邮件发送成功!")
    except Exception as e:
        print(f"邮件发送失败:{str(e)}")
    finally:
        # 关闭与邮件服务器的连接
        smtp_server.quit()

# 使用示例
sender_email = "your_email@gmail.com"  # 发件人邮箱地址
sender_password = "your_password"  # 发件人邮箱密码或授权码
recipient_email = "recipient_email@gmail.com"  # 收件人邮箱地址
subject = "测试邮件"  # 邮件主题
message = "这是一封测试邮件。"  # 邮件内容

send_email(sender_email, sender_password, recipient_email, subject, message)

在上面的示例中,我们首先创建了要发送的邮件内容。然后,使用smtplib.SMTP创建了一个与邮件服务器的连接。我们使用Gmail的SMTP服务器,但你也可以使用其他提供SMTP服务的邮件服务器。接下来,我们使用starttls方法启用TLS加密,并使用login方法登录到发送邮件的账户。最后,使用sendmail方法发送邮件,并使用quit方法关闭与邮件服务器的连接。

注意,在使用示例之前,你需要将sender_emailsender_password替换为实际的发件人邮箱地址和密码,并将recipient_email替换为收件人邮箱地址。

此外,还可以使用其他Python库,如yagmailsmtplib的高级封装email,从而更简单地发送电子邮件。以下是使用yagmail发送邮件的示例:

import yagmail

def send_email(sender_email, sender_password, recipient_email, subject, message):
    try:
        # 创建yagmail对象并发送邮件
        yag = yagmail.SMTP(sender_email, sender_password)
        yag.send(recipient_email, subject, message)
        print("邮件发送成功!")
    except Exception as e:
        print(f"邮件发送失败:{str(e)}")

# 使用示例
sender_email = "your_email@gmail.com"  # 发件人邮箱地址
sender_password = "your_password"  # 发件人邮箱密码或授权码
recipient_email = "recipient_email@gmail.com"  # 收件人邮箱地址
subject = "测试邮件"  # 邮件主题
message = "这是一封测试邮件。"  # 邮件内容

send_email(sender_email, sender_password, recipient_email, subject, message)

在上面的示例中,我们使用yagmail库来发送邮件。类似地,你需要将sender_emailsender_password替换为实际的发件人邮箱地址和密码,并将recipient_email替换为收件人邮箱地址。

总结起来,在Python中发送电子邮件的基本步骤如下:

1. 创建邮件内容(可以是纯文本、HTML或带有附件的邮件)。

2. 通过SMTP服务和邮件服务器建立连接。

3. 启用必要的加密(如TLS)。

4. 使用发件人的邮箱地址和密码进行登录。

5. 使用sendmail方法发送邮件。

6. 使用quit方法关闭与邮件服务器的连接。

希望以上信息对你有帮助!