Python Helps Me!!!

I was in trouble when I wanted my program to send email automatically as my program was writing in Javascript and XUL.
You might all know that javascript has limited ability in sending email because of security feature. But for my program, it is not web application and I needed a feature to send mail through SMTP, not using Outlook (mailto:) because I am using Linux OS. :)

I searched and searched and finally I found python. :D
Thanks to all online tutorials and blog that shared how to send mail using python script. I cannot list them because I don’t remember all and I read many many website. :) sorry for that.

I just write script file that accept parameters. And then from my program I call python and execute that script file given parameters. :) that all!!! How easy!!! I should have know early. :D

here is my script: (correct me if my code is wrong or missing something, so far it works fine)
#!/usr/bin/python
import smtplib
import base64
import sys
filename = sys.argv[9]
fo = open(filename,"rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)
FROM = sys.argv[1]
TO = sys.argv[2]
marker = "AUNIQUEMARKER"
body = sys.argv[3]
part1 = """From: %s
To: %s
Subject: %s
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (FROM,TO, sys.argv[4],marker, marker)
part2="""Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment;filename=%s
%s
--%s--
""" % (filename,filename,encodedcontent,marker)
message = part1 + part2 + part3
server=smtplib.SMTP(sys.argv[5],sys.argv[6])
server.ehlo()
server.starttls()
server.ehlo()
server.login(sys.argv[7],sys.argv[8])
server.sendmail(FROM,TO,message)
server.quit()

This script take 9 parameters; as I called python to run this script, it becomes all together 10 parameters. This script itself is parameter[0]. This script accept attachment as my program needs it.
here is how to execute from my program.
self.execute("/usr/bin/python",[script_file, sender, receivers, body, subject, smtp_host, smtp_port, smtp_username, password, attach_file]);

Of course, self.execute is customized function. :)

That’s all for today. Oh By the way, happy birthday to me. :D LOL.

Also read...

Leave a Reply