You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python邮件生成器如何读取JSON文件中的catchall并修复代码?

解决方案

1. 先搞定JSON文件的读取

首先你的JSON文件得是合法格式,比如命名为catchall.json,内容写成:

{"catchall": "@yourdomain.com"}

然后用Python的json模块读取,别写(json.data file)这种无效代码。

2. 修复email_format的问题

email_format就是你从JSON里读出来的catchall值,要确保它带@,这样和随机生成的前缀拼接后才是合法邮箱。

完整可运行代码

import string
import random
import json

def email_gen():
    # 这里可以根据需求调整生成邮箱的数量和前缀长度
    emails_number = 5
    chars = 8

    # 读取JSON中的catchall
    try:
        with open('catchall.json', 'r') as f:
            config = json.load(f)
            catchall = config.get('catchall')
            if not catchall or '@' not in catchall:
                print("JSON里的catchall配置无效,需要带@的域名后缀")
                return
    except FileNotFoundError:
        print("找不到catchall.json文件,请确认路径")
        return
    except json.JSONDecodeError:
        print("JSON文件格式错了,检查语法")
        return

    # 构建可用字符池:数字+大小写字母
    char_pool = string.digits + string.ascii_lowercase + string.ascii_uppercase

    for _ in range(emails_number):
        # 生成随机前缀
        random_prefix = ''.join(random.choices(char_pool, k=chars))
        # 拼接成完整邮箱
        full_email = random_prefix + catchall
        print(full_email)

email_gen()

核心修复点

  • 删掉了冗余的letters_list拼接,直接用string模块常量组合字符池,更高效
  • 新增了JSON读取的异常处理,覆盖文件缺失、格式错误、配置无效的情况
  • 把原来的email_format替换为从JSON读取的catchall,保证邮箱格式正确
  • 补全了email_gen函数的定义(原代码里有调用但没函数体)

内容的提问来源于stack exchange,提问作者Riccardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 18:05:32