Compare commits

..

No commits in common. "4b4121ebd8ba7ab5dbc05bd1eeff85b1a91f5203" and "5ba50405131809b73361748e769220d640cf1714" have entirely different histories.

4 changed files with 12 additions and 29 deletions

1
.gitignore vendored

@ -1,2 +1 @@
config.json config.json
*.log

@ -38,7 +38,6 @@ pip install pysocks
```json ```json
{ {
"log": "output.log",
"check_interval": 60, "check_interval": 60,
"accounts": [ "accounts": [
{ {
@ -71,7 +70,6 @@ pip install pysocks
### 配置项说明 ### 配置项说明
- `log`: 日志文件路径。
- `check_interval`: 检查邮件的时间间隔,单位为秒。 - `check_interval`: 检查邮件的时间间隔,单位为秒。
- `accounts`: 配置多个邮箱账户。 - `accounts`: 配置多个邮箱账户。
- `email`: 邮箱地址。 - `email`: 邮箱地址。

@ -1,5 +1,4 @@
{ {
"log": "output.log",
"accounts": [ "accounts": [
{ {
"enabled": false, "enabled": false,

35
main.py

@ -6,7 +6,6 @@ from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.utils import parseaddr from email.utils import parseaddr
import time import time
import datetime
import logging import logging
import socks import socks
import socket import socket
@ -39,19 +38,9 @@ def set_proxy(proxy_config):
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_config['server'], proxy_config['port']) socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy_config['server'], proxy_config['port'])
socket.socket = socks.socksocket socket.socket = socks.socksocket
def setup_logging(filename): def setup_logging():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s >> %(levelname)s - %(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler()
chlr.setFormatter(formatter)
chlr.setLevel('INFO')
fhlr = logging.FileHandler(filename)
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)
return logger return logger
def get_unforwarded_emails(account_config, logger): def get_unforwarded_emails(account_config, logger):
@ -84,8 +73,7 @@ def get_unforwarded_emails(account_config, logger):
if 'Forwarded' not in msg['Subject']: if 'Forwarded' not in msg['Subject']:
emails.append((email_id, msg)) emails.append((email_id, msg))
imap.logout() imap.logout()
if len(emails) > 0: logger.info(f"Retrieved {len(emails)} new emails from {account_config['email']}")
logger.info(f"Retrieved {len(emails)} new emails from {account_config['email']}")
return emails return emails
def forward_emails(account_config, emails, logger): def forward_emails(account_config, emails, logger):
@ -104,13 +92,9 @@ def forward_emails(account_config, emails, logger):
for email_id, original_msg in emails: for email_id, original_msg in emails:
for recipient in account_config['forward']['to']: for recipient in account_config['forward']['to']:
from_name, from_address = parseaddr(original_msg['From'])
from_name = decode_mime_words(from_name)
to_name, to_address = parseaddr(original_msg['To'])
to_name = decode_mime_words(to_name)
msg = MIMEMultipart('mixed') msg = MIMEMultipart('mixed')
msg['From'] = f"{from_name} ({from_address}) via Forwarder <{account_config['email']}>" msg['From'] = account_config['email']
msg['To'] = f"{to_name} ({to_address}) via Forwarder <{recipient}>" msg['To'] = recipient
original_subject = decode_mime_words(original_msg['Subject']) original_subject = decode_mime_words(original_msg['Subject'])
msg['Subject'] = original_subject msg['Subject'] = original_subject
@ -145,13 +129,13 @@ def forward_emails(account_config, emails, logger):
msg.attach(attachment) msg.attach(attachment)
smtp.sendmail(account_config['email'], recipient, msg.as_string()) smtp.sendmail(account_config['email'], recipient, msg.as_string())
logger.info(f"Forwarded email {original_subject} from {account_config['email']} to {recipient}") logger.info(f"Forwarded email {original_subject} to {recipient}")
smtp.quit() smtp.quit()
def main(): def main():
logger = setup_logging()
config = load_config() config = load_config()
logger = setup_logging(config['log'])
while True: while True:
for account in config['accounts']: for account in config['accounts']:
@ -160,10 +144,13 @@ def main():
emails = get_unforwarded_emails(account, logger) emails = get_unforwarded_emails(account, logger)
if emails: if emails:
forward_emails(account, emails, logger) forward_emails(account, emails, logger)
else:
logger.info(f"No new emails to forward for {account['email']}.")
except Exception as e: except Exception as e:
logger.error(f"Error processing account {account['email']}: {str(e)}") logger.error(f"Error processing account {account['email']}: {str(e)}")
else:
logger.info(f"Account {account['email']} is disabled.")
logger.info(datetime.datetime.now().strftime("Check finished at %Y-%m-%d %H:%M:%S"))
time.sleep(config.get('check_interval', 60)) time.sleep(config.get('check_interval', 60))
if __name__ == "__main__": if __name__ == "__main__":