目录
前言
1. 导入库
2. 配置邮件信息
3. 编写发送邮件函数
4. 调用发送邮件函数
前言
在当今社会,随着互联网技术的不断发展,人们越来越多地依赖于各种在线平台完成日常任务。为了提高用户体验,保障用户账户安全,很多网站和应用程序都采用了验证码技术。本文将介绍如何使用 Python 实现发送邮件通知验证码功能,希望能对读者有所帮助。
Python3.13安装环境
💾安装环境👉Python3.13.2安装包下载地址:https://pan.quark.cn/s/6ad05f574acd
Python3.13安装教程
💾安装教程👉Python3.13最新版安装教程
1. 导入库
要实现发送邮件通知验证码功能,我们需要导入 Python 中对应的库,具体如下:
import smtplib
from email.mime.text import MIMEText
2. 配置邮件信息
接下来,我们需要配置邮件的信息,包括发件人、收件人、主题以及邮件的正文内容。具体如下:
import smtplib
from email.mime.text import MIMEText# 定义邮件信息
import platformsystem = platform.system()if system == "Windows":# 如果是Windows系统,则使用下面这一行代码send_mail_fun = "send_mail_windows"
else:# 如果是Linux或者MacOS系统,则使用下面这一行代码send_mail_fun = "send_mail_linux"send_mail_fun
3. 编写发送邮件函数
接下来,我们可以编写发送邮件的函数,这里提供一个简单的例子,你可以根据自己的需求进行修改。
import smtplib
from email.mime.text import MIMEText
import randomdef send_mail_windows(send_to, send_from, subject, content):mail_host = "smtp.126.com" # 邮箱服务器地址mail_port = 465 # 使用的端口号mail_user = "your_email" # 用户名(即邮箱地址)mail_pass = "your_password" # 密码message = MIMEText(content, "html", "utf-8")message["Subject"] = subjectmessage["From"] = send_frommessage["To"] = send_totry:server = smtplib.SMTP_SSL(mail_host, mail_port)server.login(mail_user, mail_pass)server.sendmail(send_from, send_to, message.as_string())print("邮件发送成功")except Exception as e:print("邮件发送失败:", e)finally:server.quit()
4. 调用发送邮件函数
最后,我们可以在主程序中调用发送邮件函数,这里可以生成一个随机的验证码,并将其发送到指定的邮箱。
import smtplib
from email.mime.text import MIMEText
import random
import platformsystem = platform.system()if system == "Windows":# 如果是Windows系统,则使用下面这一行代码send_mail_fun = "send_mail_windows"
else:# 如果是Linux或者MacOS系统,则使用下面这一行代码send_mail_fun = "send_mail_linux"def generate_verify_code():"""生成随机验证码:return: 验证码字符串"""verify_code = ''.join(random.choices('1234567890', k=6))return verify_codedef send_mail(to_email, from_email, verify_code):"""发送邮件通知验证码:param to_email: 收件人邮箱:param from_email: 发件人邮箱:param verify_code: 验证码"""subject = "验证码 - 你的网站名称"html_content = f'<p>尊敬的用户,您的验证码是:<span style="color:#ff0000">{verify_code}</span>,请尽早使用,以免过期。</p>'send_mail_fun(to_email, from_email, subject, html_content)if __name__ == "__main__":to_email = "to_email@example.com" # 收件人邮箱from_email = "from_email@example.com" # 发件人邮箱verify_code = generate_verify_code()print("生成的验证码为:", verify_code)send_mail(to_email, from_email, verify_code)