Skip to content

Instantly share code, notes, and snippets.

@slv922
Forked from sosukeinu/send-message.py
Last active January 2, 2023 18:53
Show Gist options
  • Save slv922/7b47134949047bcd418c13d4301d3351 to your computer and use it in GitHub Desktop.
Save slv922/7b47134949047bcd418c13d4301d3351 to your computer and use it in GitHub Desktop.
PYTHON send E-mail from eml file endswith 'eml' recursively
#!/usr/bin/env python
# -*- mode: python; coding: utf-8-unix -*-
import sys
import os.path
import smtplib
import gzip
import re
from email.utils import make_msgid
from datetime import datetime
if len(sys.argv) <= 4:
print('Usage:')
print(' $ python ' + sys.argv[0] + ' server_ip mailfrom rcptto folder_or_emlfile')
print
print('Parameter:')
print(' mailfrom: MAIL FROM address.')
print(' rcptto: RCPT TO address.')
print(' emlfile: Message file in eml format. When emlfile is not specified, an empty message will be s end.')
print(' server ip: SMTP server IP')
print
print('Example:')
print(' $ python ' + sys.argv[0] + ' 127.0.0.1 [email protected] [email protected] mail.eml')
sys.exit(0)
server = sys.argv[1]
port = 25
mailfrom = sys.argv[2]
rcptto = sys.argv[3].split(',')
message = ''
msgid = "Message-ID: " + make_msgid()
def log(msg):
today = datetime.now().strftime("%y%m%d")
now = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
with open('send.log.%s' % today,'a') as f:
f.write('[%s] %s' % (now, msg)+'\n')
def sendmail(file):
if len(sys.argv) >= 4:
filename = file
if not os.path.isfile(filename):
print('[Fail] File "' + filename + '" not found.')
log('[Fail] File "' + filename + '" not found.')
sys.exit(0)
if filename.endswith('gz'):
f = gzip.open(filename)
message = f.read()
f.close()
else:
with open(filename) as f:
message = f.read()
smtp = None
try:
smtp = smtplib.SMTP(server, port)
#smtp.set_debuglevel(1)
re.sub("Message-ID: .*",msgid,message)
smtp.sendmail(mailfrom, rcptto, message)
except Exception as e:
print('[Fail] Failed to send mail: %s, %s' % (filename,str(e)))
log('[Fail] Failed to send mail: %s, %s' % (filename,str(e)))
else:
print('[OK] Succeeded to send mail: %s' % filename)
log('[OK] Succeeded to send mail: %s' % filename)
finally:
if smtp != None:
smtp.close()
def sendmail_recursively(folder):
for root, dirs, files in os.walk(folder):
for file in files:
file_path = os.path.join(root, file)
if file.endswith('eml') or file.endswith('gz'):
sendmail(file_path)
if os.path.isfile(sys.argv[4]):
sendmail(sys.argv[4])
else:
sendmail_recursively(sys.argv[4])
@slv922
Copy link
Author

slv922 commented May 15, 2017

[2017/05/15] support gzip

@slv922
Copy link
Author

slv922 commented May 18, 2017

[2017/05/18] add change message-id function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment