Skip to content

Instantly share code, notes, and snippets.

@lukele
Created June 15, 2017 20:34
Show Gist options
  • Save lukele/e53a1489335710ab2804590338290620 to your computer and use it in GitHub Desktop.
Save lukele/e53a1489335710ab2804590338290620 to your computer and use it in GitHub Desktop.
Resend a .eml file (useful for testing message loading in Mail.app)
#!/usr/bin/env python
# -*- mode: python; coding: utf-8-unix -*-
import sys
import os.path
import smtplib
def remove_headers(raw_message, headers=[]):
message = []
i = 0
for line in raw_message:
if line.strip() == "":
break
i += 1
skip = False
for h in headers:
if line.lower().startswith(h.lower()):
skip = True
break
if skip:
continue
message.append(line)
message += raw_message[i:]
return message
def send_message(filename):
global smtpserver
if not os.path.isfile(filename):
print('File "' + filename + '" not found.')
sys.exit(0)
with open(filename) as f:
message = f.readlines()
message = remove_headers(message, ["From:", "To:", "CC:", "BCC:", "Date:", "Message-ID:", "X-"])
message = "".join(message)
print "From: %s" % (mailfrom)
print "To: %s" % (rcptto)
try:
smtpserver.sendmail(mailfrom, rcptto, message)
except Exception as e:
print('Failed to send mail.')
print(str(e))
else:
print('Succeeded to send mail.')
if len(sys.argv) <= 2:
print('Usage:')
print(' $ python ' + sys.argv[0] + ' mailfrom rcptto <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 send.')
print
print('Example:')
print(' $ python ' + sys.argv[0] + ' [email protected] [email protected] mail.eml')
sys.exit(0)
server = 'localhost'
port = 25
mailfrom = sys.argv[1]
rcptto = sys.argv[2].split(',')
message = ''
if len(sys.argv) >= 4:
filenames = sys.argv[3:]
# if not os.path.isfile(filename):
# print('File "' + filename + '" not found.')
# sys.exit(0)
# with open(filename) as f:
# message = f.readlines()
try:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.set_debuglevel(1)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('user', 'pass')
for filename in filenames:
send_message(filename)
except Exception as e:
print('Failed to send mail.')
print(str(e))
else:
print('Succeeded to send mail.')
finally:
if smtpserver != None:
smtpserver.close()
@tmvtmv
Copy link

tmvtmv commented Jun 8, 2021

@rorviksam

Thanks for your solution with curl ... today it helped me out big time! :-)

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