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

Python中如何使用smtplib发送带有SSL加密的电子邮件

发布时间:2024-01-16 04:09:48

在Python中,使用smtplib库发送带有SSL加密的电子邮件可以通过以下步骤实现:

1. 导入smtplib和email模块:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

2. 创建SMTP连接对象,并指定SMTP服务器和端口号:

smtp_server = 'smtp.gmail.com'
smtp_port = 587

smtp = smtplib.SMTP(smtp_server, smtp_port)

3. 启用SSL加密连接:

smtp.starttls()

4. 登录到SMTP服务器:

smtp.login('sender@gmail.com', 'password')

5. 创建邮件内容的MIME对象,包括邮件正文、附件和图片等:

subject = '邮件主题'
message = '邮件内容'

msg = MIMEMultipart()
msg['From'] = 'sender@gmail.com'
msg['To'] = 'receiver@gmail.com'
msg['Subject'] = subject

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

# 添加附件
attachment = MIMEText('附件内容', 'plain')
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
msg.attach(attachment)

# 添加图片
with open('image.png', 'rb') as f:
    img_data = f.read()
image = MIMEImage(img_data)
image.add_header('Content-Disposition', 'attachment', filename='image.png')
msg.attach(image)

6. 发送邮件:

smtp.sendmail('sender@gmail.com', 'receiver@gmail.com', msg.as_string())

7. 关闭SMTP连接:

smtp.quit()

下面是一个完整的发送带有SSL加密的电子邮件的示例:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'sender@gmail.com'
receiver_email = 'receiver@gmail.com'
password = 'password'

def send_email():
    try:
        # 创建SMTP连接对象
        smtp = smtplib.SMTP(smtp_server, smtp_port)
        
        # 启用SSL加密连接
        smtp.starttls()
        
        # 登录SMTP服务器
        smtp.login(sender_email, password)
        
        # 创建邮件内容的MIME对象
        subject = '邮件主题'
        message = '邮件内容'
        
        msg = MIMEMultipart()
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg['Subject'] = subject

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

        # 添加附件
        attachment = MIMEText('附件内容', 'plain')
        attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
        msg.attach(attachment)

        # 添加图片
        with open('image.png', 'rb') as f:
            img_data = f.read()
        image = MIMEImage(img_data)
        image.add_header('Content-Disposition', 'attachment', filename='image.png')
        msg.attach(image)

        # 发送邮件
        smtp.sendmail(sender_email, receiver_email, msg.as_string())
        
    except Exception as e:
        print('发送邮件出错:', str(e))
        
    finally:
        # 关闭SMTP连接
        smtp.quit()

# 调用发送邮件函数
send_email()

以上就是使用smtplib发送带有SSL加密的电子邮件的Python示例。您可以根据自己的需求修改邮件内容和参数,以适应不同的场景。