Search This Blog

Wednesday, March 19, 2014

Send Mail in Python (GMAIL & YAHOO)

Programmatically sending an email is really a good tool for developer’s paraphernalia. This is really handy when one automates task and wants to get notified by an email for success or failure. Lately I have written Python script to automate some jobs and incorporated method to send email notification. I thought to share this simple script here so my readers can get benefited.

Using local MTA-SMTP connection

Python script to send email
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
EMAIL_SUBJECT = "Email from Python script"
EMAIL_FROM = "notification@code4reference.com"
EMAIL_RECEIVERS = ['your_email@gmail.com']
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(msg):
    """This method sends an email"""
   
    msg_header = "From: " + EMAIL_FROM + "\n" + \
                 "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \
                 "Subject: " + EMAIL_SUBJECT + "\n"
    msg_body =  msg_header + msg
    try:
      #establish a connection with the local SMTP server.
      smtpObj = smtplib.SMTP('localhost')
      #Now send the email
      smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
      #Close the connection and session.
      smtpObj.quit()
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main():
    """This is a simple main() function which demonstrate sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries");
if __name__ == "__main__":
   """If this script is run as stand alone then call main() function."""
    main()
Before running this script make sure your system has Mail Transfer Agent(MTA) configured. If it is not then readthis post to configure Mail-server on Ubuntu 12.04.
If you are not interested to configure your own MTA then you can probably used the SMTP service provided by other Mail server e.g Gmail, yahoo, etc. But these service providers put some email limits to control spamming. If your application/script is sending email more than this limit then the service can detect it as spamming and may lock your account. You can find gmail email limit from here whereas Yahoo SMTP limit is provided here.

Using Gmail SMTP

Google SMTP server is located here smtp.gmail.com. According to the standard the SMTP port is 25 but Gmail doesn’t use this port instead it uses port 587. Script uses this information to establish a connection and sends an email.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER  =  'senderId@gmail.com'
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
TEXT_SUBTYPE = "plain"
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(content, pswd):
    """This method sends an email"""    
     
    #Create the message
    msg = MIMEText(content, TEXT_SUBTYPE)
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_SENDER
    msg["To"] = listToStr(EMAIL_RECEIVERS)
     
    try:
      smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT)
      #Identify yourself to GMAIL ESMTP server.
      smtpObj.ehlo()
      #Put SMTP connection in TLS mode and call ehlo again.
      smtpObj.starttls()
      smtpObj.ehlo()
      #Login to service
      smtpObj.login(user=EMAIL_SENDER, password=pswd)
      #Send email
      smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
      #close connection and session.
      smtpObj.quit();
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main(pswd):
    """This is a simple main() function which demonstrates sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
    """If this script is executed as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print "Please provide password"
        sys.exit(0)
If scripts uses SMTP to send emails then Gmail can detect it as suspicious activity and it may ask you to change the password. This is a kind-of-annoying. To avoid such issues it always suggested to configure your own MTA.

Using Yahoo SMTP

Yahoo exposed SMTP service here smtp.mail.yahoo.com and 465 port. Unlike Gmail, It expects a SSL SMTP connection.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER  =  'senderId@yahoo.com'
TEXT_SUBTYPE = "plain"
YAHOO_SMTP = "smtp.mail.yahoo.com"
YAHOO_SMTP_PORT = 465
def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)
def send_email(content, pswd):
    """This method sends an email"""
    msg = MIMEText(content, TEXT_SUBTYPE)
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_SENDER
    msg["To"] = listToStr(EMAIL_RECEIVERS)
     
    try:
      #Yahoo allows SMTP connection over SSL.
      smtpObj = SMTP_SSL(YAHOO_SMTP, YAHOO_SMTP_PORT)
      #If SMTP_SSL is used then ehlo and starttls call are not required.
      smtpObj.login(user=EMAIL_SENDER, password=pswd)
      smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
      smtpObj.quit();
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)
def main(pswd):
    """This is a simple main() function which demonstrates sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
    """If this script is executed as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print "Please provide password"
        sys.exit(0)

Email with attachment

Above scripts just send an email what if you want to attach something with it. You can use the below script to attach a picture and text file with the email.

#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTPException
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import sys


EMAIL_SUBJECT = "Email from Python script with attachment."
EMAIL_FROM = 'senderId@gmail.com'
EMAIL_RECEIVER = 'receiverId@gmail.com'
GMAIL_SMTP = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587
TEXT_SUBTYPE = "plain"

def listToStr(lst):
    """This method makes comma separated list item string"""
    return ','.join(lst)

def send_email(content, pswd):
    """This method sends an email"""

    #Create the email.
    msg = MIMEMultipart()
    msg["Subject"] = EMAIL_SUBJECT
    msg["From"] = EMAIL_FROM
    msg["To"] = EMAIL_RECEIVER
    body = MIMEMultipart('alternative')
    body.attach(MIMEText(content, TEXT_SUBTYPE ))
    #Attach the message
    msg.attach(body)
    #Attach a text file
    msg.attach(MIMEText(file("code4reference.txt").read()))
    #Attach a picuture.
    msg.attach(MIMEImage(file("pic.jpg").read()))

    try:
      smtpObj = SMTP(GMAIL_SMTP, GMAIL_SMTP_PORT)
      #Identify yourself to GMAIL ESMTP server.
      smtpObj.ehlo()
      #Put SMTP connection in TLS mode and call ehlo again.
      smtpObj.starttls()
      smtpObj.ehlo()
      #Login to service
      smtpObj.login(user=EMAIL_FROM, password=pswd)
      #Send email
      smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVER, msg.as_string())
      #close connection and session.
      smtpObj.quit()
    except SMTPException as error:
      print "Error: unable to send email :  {err}".format(err=error)

def main(pswd):
    """This is a simple main() function which demonstrate sending of email using smtplib."""
    send_email("Test email was generated by Python using smtplib and email libraries." + \
               " This email also has attachments. Please download them", pswd);

if __name__ == "__main__":
    """If this script is run as stand alone then call main() function."""
    if len(sys.argv) == 2:
        main(sys.argv[1]);
    else:
        print "Please provide the password"


------------------------------------------------------------------------------------------------------------------------
If you are interested in source code you can get it from github/code4reference
Hope this blog helped you in some way but don't than me as owner is Mr. Rakesh

Original blog url is Link









Saturday, March 31, 2012

To Mount remote windows partition (windows share) under Linux


All files accessible in a Linux (and UNIX) system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the file system found on some device to the big file tree.
Use the mount command to mount remote windows partition or windows share under Linux as follows:

Procedure to mount remote windows partition (NAS share)

1) Make sure you have following information:
==> Windows username and password to access share name
==> Sharename (such as //server/share) or IP address
==> root level access on Linux
2) Login to Linux as a root user (or use su command)
3) Create the required mount point:
# mkdir -p /mnt/ntserver
4) Use the mount command as follows:
# mount -t cifs //ntserver/download -o username=vivek,password=myPassword /mnt/ntserver
Use following command if you are using Old version such as RHEL <=4 or Debian <= 3:
# mount -t smbfs -o username=vivek,password=D1W4x9sw //ntserver/download /mnt/ntserver
5) Access Windows 2003/2000/NT share using cd and ls command:
# cd /mnt/ntserver; ls -l
Where,
  • -t smbfs : File system type to be mount (outdated, use cifs)
  • -t cifs : File system type to be mount
  • -o : are options passed to mount command, in this example I had passed two options. First argument is password (vivek) and second argument is password to connect remote windows box
  • //ntserver/download : Windows 2000/NT share name
  • /mnt/ntserver Linux mount point (to access share after mounting)

Thursday, March 29, 2012

SugarCRM installation in UBUNTU

Installing SugarCRM Community Edition On Ubuntu 8.10
Version 1.0
Author: Falko Timme  
Last edited 01/07/2009
SugarCRM is a webbased CRM solution written in PHP. SugarCRM is available in different flavours called "Editions" ("Community" (free), "Professional", and "Enterprise"). For a detailed overview of the different editions, have a look at the SugarCRM website. In this tutorial I will describe the installation of the free Community Edition on Ubuntu 8.10. With the modules My PortalCalendarActivitiesContactsAccountsLeadsOpportunitiesCasesBugtrackerDocuments and Email, SugarCRM Community Edition offers everything that can be expected from a CRM solution.

1 Preliminary Note

In this tutorial I use the hostname server1.example.com with the IP address 192.168.0.100. These settings might differ for you, so you have to replace them where appropriate.
I will install SugarCRM in Apache's default vhost (document root /var/www) in the directory /var/www/sugarcrm. you might have to adjust this on your system.
Make sure that you are logged in as root (type in
sudo su
to become root), because we must run all the steps from this tutorial as root user.

2 Install The MySQL Database Server

Install unzip to be able to unpack the SugarCRM package later:
apt-get install unzip
Install MySQL:
apt-get install mysql-server mysql-client
You will be asked the following questions:
New password for the MySQL "root" user: <-- yourrootsqlpassword (a password of your choice)
Repeat password for the MySQL "root" user: <-- yourrootsqlpassword

3 Install The Apache Webserver And PHP

apt-get install apache2 apache2-doc apache2-mpm-prefork apache2-utils libexpat1 libapache2-mod-php5 php5-common php5-gd php5-idn php-pear php5-imap php5-mcrypt php5-mhash php5-mysql php5-sqlite php5-xmlrpc php5-xsl php5-curl
Afterwards we need to modify two settings in /etc/php5/apache2/php.ini:
vi /etc/php5/apache2/php.ini
Set the memory_limit to 64M (or more) and the upload_max_filesize to 20M:
[...]
;memory_limit = 16M      ; Maximum amount of memory a script may consume (16MB)
memory_limit = 64M
[...]
; Maximum allowed size for uploaded files.
;upload_max_filesize = 2M
upload_max_filesize = 20M
[...]
Restart Apache afterwards:
/etc/init.d/apache2 restart

4 Install SugarCRM

You can download SugarCRM Community Edition from http://www.sugarforge.org/frs/?group_id=6 or http://www.sugarcrm.com/crm/download/sugar-suite.html. Pick the latest .zip file (version 5.2.0 at the time of this wrinting) and install it as follows:
mkdir /var/www/sugarcrm
cd /tmp
wget http://www.sugarforge.org/frs/download.php/4902/SugarCE-5.2.0.zip
unzip SugarCE-5.2.0.zip
cd SugarCE-Full-5.2.0/
mv * /var/www/sugarcrm/
chown -R www-data:www-data /var/www/sugarcrm
Start the webbased SugarCRM installer by opening the URL http://server1.example.com/sugarcrm or http://192.168.0.100/sugarcrm in your browser.
The SugarCRM setup wizard comes up:

Scroll down and click on the Next button:

Accept the license (GPL) and click on Next:

Select Typical Install and click on Next:


Tuesday, March 13, 2012

What is Umask


When user create a file or directory under Linux or UNIX, she create it with a default set of permissions. In most case the system defaults may be open or relaxed for file sharing purpose. For example, if a text file has 666 permissions, it grants read and write permission to everyone. Similarly a directory with 777 permissions, grants read, write, and execute permission to everyone.

Default umask Value

The user file-creation mode mask (umask) is use to determine the file permission for newly created files. It can be used to control the default file permission for new files. It is a four-digit octal number. A umask can be set or expressed using:
  • Symbolic values
  • Octal values