Email Keep-Alive Procedure-Tongyi Qianwen
"TLDR: This article introduces the method of implementing the mailbox keep-alive program through Tongyi Qianwen, and gives detailed code examples."
It has been two or three months since graduation, and it suddenly occurred to me that some schools will cancel the edu mailbox after students graduate, and some schools will take back the mailbox if it is not used for a long time. Thinking about the github education package that I bought for free, and other members who bought it for free through the edu mailbox, I felt that this mailbox was still very important, so I planned to write a keep-alive program and send an email every other month to prove that the mailbox is still in use.
It is impossible to write the code completely by yourself, so start GPT directly. This time I chose Tongyi Qianwen. Overall, I feel very good. The domestic large-scale model is quite satisfactory in terms of coding capabilities. After a few rounds of dialogue, I wrote the desired program. There are basically no major mistakes. It can be deployed to the production environment with minor changes.
In addition, Tongyi Qianwen also thoughtfully recommends using cron scheduled tasks to avoid running Python programs for a long time and consuming resources. This is true, it only runs once every other month, and time.sleep for a month is not a problem. Tongyi Qianwen also recommends not to hard-code accounts and passwords in the code. It is recommended to store this sensitive information in environment variables or encrypt it and put it in the configuration file. All in all, it's quite considerate.
The following is the code generated by AI after minor changes:
import smtplib
from email.mime.text import MIMEText
import imaplib
import logging
importyaml
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."):
# Create SMTP object and log in to the server
server = smtplib.SMTP_SSL(config['smtp_server'], config['smtp_port'])
server.login(sender, app_password)
# Build email
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
# Send email
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):
# Connect to IMAP server
mail = imaplib.IMAP4_SSL(config['imap_server'])
mail.login(user, app_password)
mail.select("inbox")
#Search for unread emails
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 # declare global variables
config = load_config('config.yml') #Load configuration file
#Configuration
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()