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

用Python编写简单的邮件发送程序

发布时间:2023-12-04 19:20:49

编写邮件发送程序可以使用Python的smtplib库。smtplib库提供了用于SMTP(简单邮件传输协议)客户端的方法和类,可以使用它来发送邮件。

首先,需要导入smtplib库和email库。email库提供了一些类和方法,用于构建和处理电子邮件。

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

接下来,需要设置发送邮件所需的一些参数,包括SMTP服务器地址、端口号、发件人邮箱、发件人姓名、收件人邮箱、邮件主题和正文内容。

smtp_server = 'smtp.example.com'
smtp_port = 587
sender_email = 'sender@example.com'
sender_name = 'Sender Name'
recipient_email = 'recipient@example.com'
subject = 'Example Subject'
body = 'Example Body'

然后,创建一个MIMEText对象,用于表示邮件内容。MIMEText类可以指定邮件的文本内容和MIME子类型(例如,html、plain等)。

message = MIMEText(body, 'plain')

接下来,需要设置邮件的发件人和收件人信息。

message['From'] = formataddr((sender_name, sender_email))
message['To'] = recipient_email
message['Subject'] = subject

接着,需要进行邮件的发送。首先,创建一个SMTP对象,并与SMTP服务器建立连接。然后,使用login()方法进行登录,提供发件人邮箱和密码。最后,使用sendmail()方法发送邮件,提供发件人邮箱、收件人邮箱和邮件内容。

try:
    with smtplib.SMTP(smtp_server, smtp_port) as smtp:
        smtp.starttls()
        smtp.login(sender_email, 'password')
        smtp.sendmail(sender_email, [recipient_email], message.as_string())
        print('邮件发送成功')
except smtplib.SMTPException as e:
    print('邮件发送失败:', e)

这是一个简单的邮件发送程序的示例。请注意,需要根据实际情况替换示例中的参数,如SMTP服务器地址、端口号、发件人邮箱、收件人邮箱和密码等。

下面是一个完整的使用示例:

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

smtp_server = 'smtp.example.com'
smtp_port = 587
sender_email = 'sender@example.com'
sender_name = 'Sender Name'
recipient_email = 'recipient@example.com'
subject = 'Example Subject'
body = 'Example Body'

message = MIMEText(body, 'plain')
message['From'] = formataddr((sender_name, sender_email))
message['To'] = recipient_email
message['Subject'] = subject

try:
    with smtplib.SMTP(smtp_server, smtp_port) as smtp:
        smtp.starttls()
        smtp.login(sender_email, 'password')
        smtp.sendmail(sender_email, [recipient_email], message.as_string())
        print('邮件发送成功')
except smtplib.SMTPException as e:
    print('邮件发送失败:', e)

请注意,实际使用时需要将代码中的'smtp.example.com''sender@example.com''recipient@example.com''password'替换为实际的SMTP服务器地址、发件人邮箱、收件人邮箱和密码。

以上是使用Python编写简单的邮件发送程序的步骤和示例。你可以根据自己的需求进一步扩展代码,例如添加邮件附件、使用HTML格式的邮件内容等。