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

使用Pythonemail.mime.text模块发送简单的文本邮件

发布时间:2023-12-16 18:00:28

以下是使用Python's email.mime.text模块发送简单的文本邮件的例子。

首先,我们需要导入所需的模块和创建相应的邮件对象:

import smtplib
from email.mime.text import MIMEText

# 创建邮件对象
msg = MIMEText('This is a simple text email.', 'plain')
msg['Subject'] = 'Simple Text Email'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'

接下来,我们需要设置SMTP服务器和凭据:

smtp_server = 'smtp.example.com'
username = 'your_email@example.com'
password = 'your_password'

然后,我们使用smtplib模块创建一个与SMTP服务器的连接并发送邮件:

try:
    server = smtplib.SMTP(smtp_server)
    server.login(username, password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()
    print('Email sent successfully!')
except Exception as e:
    print('Failed to send email:', str(e))

完整的代码如下:

import smtplib
from email.mime.text import MIMEText

# 创建邮件对象
msg = MIMEText('This is a simple text email.', 'plain')
msg['Subject'] = 'Simple Text Email'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'

# 设置SMTP服务器和凭据
smtp_server = 'smtp.example.com'
username = 'your_email@example.com'
password = 'your_password'

#发送邮件
try:
    server = smtplib.SMTP(smtp_server)
    server.login(username, password)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.quit()
    print('Email sent successfully!')
except Exception as e:
    print('Failed to send email:', str(e))

请确保将 your_email@example.comrecipient@example.com 更改为有效的电子邮件地址,并将 smtp.example.com更改为实际的SMTP服务器。

这个例子中,我们创建了一个简单的文本邮件并发送它。您可以根据自己的需要修改邮件内容、主题、发件人、收件人等。