Python基于QQ邮箱实现SSL发送攻略
1. 准备工作
在开始之前,确保你已经安装了Python,并且拥有一个QQ邮箱账号。
2. 安装必要的库
使用Python发送SSL邮件需要使用到smtplib
和ssl
库。你可以使用以下命令来安装它们:
pip install smtplib
pip install ssl
3. 导入库
在Python脚本中,导入所需的库:
import smtplib
import ssl
4. 设置邮箱信息
在脚本中设置发送邮件所需的邮箱信息,包括SMTP服务器地址、端口号、发件人邮箱地址和密码。以QQ邮箱为例:
smtp_server = \"smtp.qq.com\"
port = 465
sender_email = \"your_email@qq.com\"
password = \"your_password\"
5. 创建SSL连接
使用ssl
库创建一个SSL连接:
context = ssl.create_default_context()
6. 发送邮件
使用smtplib
库发送邮件。以下是一个示例,发送一封简单的文本邮件:
receiver_email = \"recipient@example.com\"
message = \"\"\"\\
Subject: Hello from Python!
This is a test email sent from Python.\"\"\"
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
7. 示例说明
示例1:发送带附件的邮件
以下示例演示如何发送带附件的邮件:
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
receiver_email = \"recipient@example.com\"
subject = \"Email with Attachment\"
body = \"This email contains an attachment.\"
# 创建邮件对象
message = MIMEMultipart()
message[\"From\"] = sender_email
message[\"To\"] = receiver_email
message[\"Subject\"] = subject
# 添加正文
message.attach(MIMEText(body, \"plain\"))
# 添加附件
attachment_path = \"path/to/attachment.txt\"
with open(attachment_path, \"rb\") as attachment:
part = MIMEApplication(attachment.read())
part.add_header(\"Content-Disposition\", \"attachment\", filename=os.path.basename(attachment_path))
message.attach(part)
# 发送邮件
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
示例2:发送HTML格式的邮件
以下示例演示如何发送HTML格式的邮件:
from email.mime.text import MIMEText
receiver_email = \"recipient@example.com\"
subject = \"HTML Email\"
html_body = \"<h1>This is an HTML email.</h1>\"
# 创建邮件对象
message = MIMEText(html_body, \"html\")
message[\"From\"] = sender_email
message[\"To\"] = receiver_email
message[\"Subject\"] = subject
# 发送邮件
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
以上就是使用Python基于QQ邮箱实现SSL发送的完整攻略。你可以根据自己的需求进行修改和扩展。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python基于QQ邮箱实现SSL发送 - Python技术站