Skip to content

Instantly share code, notes, and snippets.

@sosukeinu
Forked from ser1zw/send-message.py
Created December 24, 2012 17:38
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save sosukeinu/4370139 to your computer and use it in GitHub Desktop.
Save sosukeinu/4370139 to your computer and use it in GitHub Desktop.
PYTHON send E-mail from eml file
#!/usr/bin/env python
# -*- mode: python; coding: utf-8-unix -*-
import sys
import os.path
import smtplib
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] + ' mailfrom@example.com rcptto@example.com mail.eml')
sys.exit(0)
server = 'localhost'
port = 25
mailfrom = sys.argv[0]
rcptto = sys.argv[1].split(',')
message = ''
if len(sys.argv) >= 4:
filename = sys.argv[3]
if not os.path.isfile(filename):
print('File "' + filename + '" not found.')
sys.exit(0)
with open(filename) as f:
message = f.read()
smtp = None
try:
smtp = smtplib.SMTP(server, port)
smtp.sendmail(mailfrom, rcptto, message)
except Exception as e:
print('Failed to send mail.')
print(str(e))
else:
print('Succeeded to send mail.')
finally:
if smtp != None:
smtp.close()
@BadgerCode
Copy link

Line #22 should be sys.argv[1]
Line #23 should be sys.argv[2]

@sohamLTD
Copy link

sohamLTD commented Jul 9, 2018

thanks! Works as expected in python3

@jnicoles1
Copy link

It works , how to add to and subject to the email

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