如何通过电子邮件别名接收电子邮件并将其保存到数据库

47 阅读2分钟

我需要创建一个网络应用程序,其中任何人可以向我的域中的任何电子邮件地址发送电子邮件。例如,可以发送到 123@example.comabc321@examle.com。当收到电子邮件时,我想获取它,检测地址(如“123”或“abc321”)并将该电子邮件信息添加到数据库中。或者,调用一个特殊功能从邮件中解析出必要的字段并发送到数据库。所以,最终我需要在数据库中保存:目标地址、主题、邮件正文和发送者地址。我需要帮助来实现这个功能。

huake_00152_.jpg

2、解决方案

一种常见的解决方案是使用电子邮件服务器中的“垃圾箱”功能,它可以将所有发送到该域的电子邮件都转发到一个指定的邮箱中。然后,您可以使用一个 Python 脚本登录到这个邮箱,并处理这些电子邮件。

以下是一些可能的解决方案:

  1. 设置一个电子邮件服务器,并配置一个“垃圾箱”邮箱。这样,所有发送到该域的电子邮件都将被转发到“垃圾箱”邮箱中。
  2. 使用一个 Python 脚本登录到“垃圾箱”邮箱,并处理这些电子邮件。该脚本可以解析电子邮件,并将其中的内容提取出来,例如:目标地址、主题、邮件正文和发送者地址。然后,将这些内容添加到数据库中。
  3. 您也可以使用第三方服务来接收和处理电子邮件,例如:Google Apps for Business 或 Microsoft 365。这些服务通常都提供“垃圾箱”功能,并且可以轻松地与 Python 脚本集成。

以下是代码示例:

import imaplib
import email

def get_emails_from_inbox(hostname, username, password):
  """
  Gets all emails from the inbox of an email account.

  Args:
    hostname: The hostname of the email server.
    username: The username of the email account.
    password: The password of the email account.

  Returns:
    A list of email messages.
  """

  # Connect to the email server
  imap_server = imaplib.IMAP4_SSL(hostname)
  imap_server.login(username, password)

  # Select the inbox folder
  imap_server.select('Inbox')

  # Get all email messages in the inbox
  status, data = imap_server.search(None, 'ALL')
  email_ids = data[0].split()

  # Get the email messages
  emails = []
  for email_id in email_ids:
    status, data = imap_server.fetch(email_id, '(RFC822)')
    email_message = email.message_from_bytes(data[0][1])
    emails.append(email_message)

  # Logout from the email server
  imap_server.logout()

  return emails

def save_email_to_database(email_message):
  """
  Saves an email message to a database.

  Args:
    email_message: The email message to save.
  """

  # Extract the email fields
  to_address = email_message['To']
  subject = email_message['Subject']
  body = email_message.get_payload()
  from_address = email_message['From']

  # Add the email fields to the database
  database_connection.execute("INSERT INTO emails (to_address, subject, body, from_address) VALUES (?, ?, ?, ?)", (to_address, subject, body, from_address))

# Get the emails from the inbox
emails = get_emails_from_inbox('imap.example.com', 'username', 'password')

# Save the emails to the database
for email in emails:
  save_email_to_database(email)

请注意,此代码示例仅用于演示如何使用 Python 脚本接收和处理电子邮件。在实际应用中,您可能需要根据您的具体需求来修改代码。