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

邮件发送:Python实现的邮件发送函数,如发送普通邮件、附件邮件等。

发布时间:2023-09-07 09:51:45

Python是一种强大的编程语言,提供了许多库和模块来实现各种功能,包括邮件发送。在Python中,我们可以使用内置库smtplib和email来发送各种类型的邮件,包括普通文本邮件和带附件的邮件。

首先,我们需要导入smtplib和email库:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

接下来,我们需要设置发送方和接收方的相关信息,包括邮件服务器、端口号、登录凭据等。这些信息可以根据你的实际需求来设置。

email_user = 'your_email@example.com'
email_password = 'your_password'
email_send = 'recipient@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587

然后,我们可以定义一个发送普通文本邮件的函数:

def send_text_email():
    subject = 'This is the subject'
    body = 'This is the body of the email'
    msg = f'Subject: {subject}

{body}'

    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(email_user, email_password)
    server.sendmail(email_user, email_send, msg)
    server.quit()

在这个函数中,我们首先设置邮件的主题和正文内容,然后使用SMTP服务器和端口号来实例化一个SMTP对象。使用starttls()方法启用TLS加密,然后使用login()方法进行登录。最后,使用sendmail()方法发送邮件,发送方为email_user,接收方为email_send。发送完成后,我们使用quit()方法关闭连接。

除了发送普通文本邮件,我们还可以发送带附件的邮件。下面是一个发送带附件邮件的函数例子:

def send_attachment_email():
    subject = 'This is the subject'
    body = 'This is the body of the email'

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = email_send
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    filename = 'attachment.txt'
    attachment = open(filename, 'rb')

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    msg.attach(part)

    text = msg.as_string()
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(email_user, email_password)
    server.sendmail(email_user, email_send, text)
    server.quit()

在这个函数中,我们首先设置邮件的主题和正文内容。然后,我们创建一个MIMEMultipart对象,并设置发件人、收件人和主题。我们使用MIMEText将正文内容添加到MIMEMultipart对象中。接下来,我们打开要附加的文件并创建一个MIMEBase对象,将附件文件的内容添加到MIMEBase对象的payload中,设置附件的内容类型和文件名,并将其附加到MIMEMultipart对象中。将MIMEMultipart对象转换为字符串,并使用sendmail()方法发送。发送完成后,关闭连接。

以上就是使用Python实现邮件发送的基本步骤和示例代码。你可以根据自己的需求进行修改和定制。希望对你有所帮助!