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

Python中使用connect()函数连接SMTP服务器发送邮件

发布时间:2023-12-16 16:22:41

在Python中使用smtplib模块中的SMTP类可以连接SMTP服务器发送邮件。SMTP类提供了connect()函数用于连接到指定的SMTP服务器。

connect()函数的用法如下:

import smtplib

smtp_server = "smtp.example.com"
smtp_port = 587

smtp_conn = smtplib.SMTP(smtp_server, smtp_port)

其中,smtp_server变量是要连接的SMTP服务器的地址,smtp_port变量是SMTP服务器的端口号。默认情况下,SMTP服务器的端口号为25,如果SMTP服务器使用了其他非默认端口号,就需要指定端口号。

下面是一个完整的示例代码,演示如何连接SMTP服务器并发送邮件:

import smtplib
from email.mime.text import MIMEText

def send_email(to, subject, body):
    smtp_server = "smtp.example.com"
    smtp_port = 587
    smtp_username = "your_username"
    smtp_password = "your_password"

    msg = MIMEText(body)
    msg["Subject"] = subject
    msg["From"] = smtp_username
    msg["To"] = to

    smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
    smtp_conn.ehlo()
    smtp_conn.starttls()
    smtp_conn.ehlo()
    smtp_conn.login(smtp_username, smtp_password)
    smtp_conn.sendmail(smtp_username, to, msg.as_string())
    smtp_conn.quit()


to = "recipient@example.com"
subject = "Test Email"
body = "This is a test email."

send_email(to, subject, body)

在示例代码中,我们首先定义了一个名为send_email()的函数,该函数接受三个参数:收件人的电子邮件地址,邮件的主题和邮件的主体内容。然后,我们指定SMTP服务器的地址、端口、用户名和密码。接下来,我们创建一个MIMEText对象,用于构建邮件内容。然后,我们使用SMTP类的connect()函数连接到SMTP服务器,并使用ehlo()函数和starttls()函数进行必要的身份验证和加密操作。最后,我们使用login()函数登录到SMTP服务器,并使用sendmail()函数发送邮件。最后,我们使用quit()函数断开与SMTP服务器的连接。

这是一个简单的示例,演示了如何使用connect()函数连接SMTP服务器发送邮件。根据实际需求,可能需要处理更复杂的邮件内容、添加附件等。有关更详细的信息,请查阅Python官方文档和smtplib模块的文档。