How can we implement an email sending service using Python?

Python has the smtplib module which can be used to send email services. Here is a simple example:

import smtplib
from email.mime.text import MIMEText

def send_email(subject, message, to_email):
    # 邮件内容
    email_message = MIMEText(message)
    email_message["Subject"] = subject
    email_message["From"] = "sender@example.com"
    email_message["To"] = to_email

    # 发送邮件
    with smtplib.SMTP("smtp.example.com", 587) as smtp:
        smtp.login("username", "password")
        smtp.send_message(email_message)

# 调用函数发送邮件
send_email("测试邮件", "这是一封测试邮件。", "recipient@example.com")

In the above code, we first imported the smtplib module and the MIMEText class. After that, we defined a function called send_email which takes three parameters: email subject, email content, and recipient email address.

Within the function, an instance of the MIMEText object is created first, with the email subject, sender address, and recipient address set. Then, an SMTP connection is established using the smtplib.SMTP class, and the login method is called for authentication. Finally, the smtp.send_message method is used to send the email.

It is necessary to modify email parameters according to the actual situation, such as SMTP server address, login username, and password.

bannerAds