邮箱保活程序-通义千问

·3799·8 分钟·
AI摘要: 本文介绍了通过通义千问实现邮箱保活程序的方法,并给出了详细的代码示例。

毕业也有两三个月了,突然想起来有的学校会在学生毕业之后取消掉edu邮箱,有的学校是如果长时间不使用就收回邮箱。想想自己白嫖来的github教育包,还有其他通过edu邮箱白嫖来的会员,感觉这个邮箱还是很重要的,所以就打算写一个保活程序,每隔一个月发一个邮件证明邮箱还在使用。

写代码是不可能完全自己写的,所以直接GPT启动。这次选择通义千问,总体下来感觉还是非常好的,国产大模型在代码能力上令人比较满意,在几轮对话下来就写出了想要的程序,还基本没有太大错误,小改一下就能部署到生产环境上。

此外,通义千问还贴心地建议使用cron定时任务,避免长时间运行Python程序消耗资源。这倒也是,也就每隔一个月才跑一次,time.sleep一个月也不是个事。通义千问还建议不要在代码中硬编码账户和密码,建议将这些敏感信息存入环境变量或者加密之后放入配置文件中。总之还是比较贴心的。

下面是小改之后AI生成的代码:



import smtplib


from email.mime.text import MIMEText


import imaplib


import logging


import yaml








logging.basicConfig(filename='email_keep_alive.log', level=logging.INFO,


                    format='%(asctime)s - %(levelname)s - %(message)s')





def load_config(config_file_path):


    with open(config_file_path, 'r') as file:


        config = yaml.safe_load(file)


    return config





def send_email(sender, app_password, recipient, subject="Auto-Keep Alive", message="This is an auto-generated message to keep the account active."):


    # 创建SMTP对象并登录到服务器


    server = smtplib.SMTP_SSL(config['smtp_server'], config['smtp_port'])


    server.login(sender, app_password)





    # 构建邮件


    msg = MIMEText(message)


    msg['Subject'] = subject


    msg['From'] = sender


    msg['To'] = recipient





    # 发送邮件


    try:


        server.sendmail(sender, [recipient], msg.as_string())


        server.quit()


        logging.info("Email sent successfully.")


        return True


    except Exception as e:


        logging.error(f"Failed to send email: {e}")


        server.quit()


        return False





def check_email(user, app_password):


    # 连接到IMAP服务器


    mail = imaplib.IMAP4_SSL(config['imap_server'])


    mail.login(user, app_password)


    mail.select("inbox")





    # 搜索未读邮件


    result, data = mail.uid('search', None, "UNSEEN")


    if result == 'OK':


        unseen_msg_nums = data[0].split()


        logging.info(f"Found {len(unseen_msg_nums)} new messages.")


        for num in unseen_msg_nums:


            typ, data = mail.uid('fetch', num, '(RFC822)')


            if typ == 'OK':


                raw_email = data[0][1]


                logging.info(f"Received: {raw_email}")


    mail.logout()





def notify(notification_sender, notification_app_password, notification_recipient, status, message):


    subject = f"Email Notification - {status}"


    body = message


    send_email(notification_sender, notification_app_password, notification_recipient, subject, body)





def main():


    global config  # 声明全局变量


    config = load_config('config.yml')  # 加载配置文件





    # 配置


    email = config['email']


    notification = config['notification']





    try:


        logging.info("Sending email...")


        success = send_email(email['username'], email['app_password'], email['recipient'])


        if success:


            notify(notification['sender'], notification['app_password'], notification['recipient'], "Success", "The email was sent successfully.")


        else:


            notify(notification['sender'], notification['app_password'], notification['recipient'], "Failure", "There was a problem sending the email.")





        logging.info("Checking for new emails...")


        check_email(email['username'], email['app_password'])


    except Exception as e:


        logging.error(f"An error occurred: {e}")


        notify(notification['sender'], notification['app_password'], notification['recipient'], "Error", f"An unexpected error occurred: {e}")





if __name__ == "__main__":


    main()