Feb-08-2017, 02:29 PM
hi folks i am new to python and getting below error when i call my python function thru shell scripting. for some reason it doesnt likes the s_body="test kajdsfkj"
Error:------------------------ error unrecognized arguments: kajdsfkj
usage: pemail.py [-h] [-f FRM] [-t TO] [-s SUBJECT] [-b BODY] [-a ATTACHMENT]
pemail.py: error: [b]unrecognized arguments: kajdsfkj[/b]------------------------- saved below code as pmail.sh#!/bin/sh s_email='[email protected]' s_body="test kajdsfkj" s_attachment='/tmp/test3.txt' python pemail.py -t $s_email -s $s_subject -b $s_body -a $s_attachment > /home/xxx/mytest/logs/email.$(date +"%Y%m%d%H%M%S").log------------------------- saved below python code to pmail.py
#!/usr/bin/python
import boto3
import sys
import csv
import os
#import optparse
import argparse
import re
import email.utils
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.Utils import parseaddr, formataddr
from email.utils import getaddresses
def pemail(args):
print args.to
print args.subject
print args.body
print args.attachment
xfilename = os.path.basename(args.attachment)
#recipients = [ args.to ]
recipients = args.to.split(',')
#strbody = args.body.split(',')
msg=MIMEMultipart()
msg['Subject'] = args.subject
#msg['Subject'] = my_string
msg['From'] = args.frm
msg['To'] = ",".join(recipients)
msg.preable = 'Multipart message.\n'
emailbody = args.body
endline ="\n NOTE: this is an automated e-mail, please do not reply to this address as it is not monitored."
xdata = unicode( emailbody + "\n" + endline )
part = MIMEText(xdata)
msg.attach(part)
part = MIMEApplication(open(args.attachment, 'r').read(), Name=xfilename)
part.add_header('Content-Disposition', 'attachment; filename='+xfilename)
msg.attach(part)
ses = boto3.client('ses')
response = ses.send_raw_email(
Source = msg['From'],
Destinations= recipients ,
RawMessage={
'Data': msg.as_string()
}
)
print response
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
print 'Success'
else:
print 'Email failed.'
if __name__ == '__main__':
## Setup and parse command line arguments
parser = argparse.ArgumentParser(prog='pemail.py', description='Sends an email with an attachment.')
parser.add_argument('-f', '--frm', default='[email protected]', help='The sender address.')
parser.add_argument('-t', '--to', help='The recipient address.')
parser.add_argument('-s', '--subject', help='The subject of the email.')
parser.add_argument('-b', '--body', help='The body of the email.')
##parser.add_argument('-b', '--body', type=str, required=True)
parser.add_argument('-a', '--attachment', help='The path to the attachment.')
args=parser.parse_args()
pemail(args)
