Top Ad unit 728 × 90


Send Email And Receive Email By Raspberry Python

On Raspberry Pi we very easy to access Gmail email and use IMAP protocol for sending & receving email.

Then follow bellow step:


Step1: Install SSMTP
  sudo apt-get install ssmtp mailutils mpack

Step2: Edit ssmtp.conf file
  sudo nano /etc/ssmtp/ssmtp.conf
  mailhub=smtp.gmail.com:587
  hostname=ENTER YOUR RPI'S HOST NAME HERE
  AuthUser=YOU@gmail.com
  AuthPass=PASSWORD
  useSTARTTLS=YES

Step3:Sending email source code
#-----------METHOD 1--------------------------------
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("YOUR EMAIL ADDRESS", "YOUR PASSWORD")
msg = "YOUR MESSAGE!"
server.sendmail("YOUR EMAIL ADDRESS", "THE EMAIL ADDRESS TO SEND TO", msg)
server.quit()
#-----------METHOD 2---------------------------
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "YOUR ADDRESS"
toaddr = "ADDRESS YOU WANT TO SEND TO"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
 body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))
 server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

server.quit()
#--------------METHOD3-------SEND EMAIL WITH ATTACH FILE--------------------------------------
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "YOUR EMAIL"
toaddr = "EMAIL ADDRESS YOU SEND TO"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"
body = "TEXT YOU WANT TO SEND"
msg.attach(MIMEText(body, 'plain'))
filename = "NAME OF THE FILE WITH ITS EXTENSION"
attachment = open("PATH OF THE FILE", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

server.quit()
Step4: Receive email code
import imaplib
import email
import time

def checkEmail():
    mail = imaplib.IMAP4_SSL('imap.gmail.com');
    mail.login('raspberrypi_emailid@gmail.com','raspberrypi_password');
    mail.list();  # Gives list of folders or labels in gmail.        
    count = 0
    while count < 6:
        try:
            # Connect to inbox
            mail.select("inbox");    
            # Search for an unread email from user's email address
            result, data = mail.search(None,'(UNSEEN FROM "my_email_id@gmail.com")');  
            ids = data[0]   # data is a list
            id_list = ids.split() # ids is a space separated string
            latest_email_id = id_list[-1] # get the latest
            result, data = mail.fetch(latest_email_id, "(RFC822)");
            raw_email = data[0][1];
            recv_msg = email.message_from_string(raw_email)
            if(recv_msg['Subject'] == "Allow person"):
                print("The person has been granted access. Hurray!!!")
            else:
                print("ACCESS DENIED!!!")               
            count = 6
        except IndexError:
            time.sleep(30*1)
            if count < 5:
                count = count + 1
                continue
            else:
                print("Sorry,No reply in the last 3 minutes.")
                count = 6        
checkEmail()

//ADDITIONAL INSTRUCTION

Send Email with a Raspberry Pi


Sending email with a Raspberry Pi Python program can be very useful when you want an alert, to receive a set of results or find out if a set of conditions have been reached among other things. To achieve this we need to create a python script that uses the smtplib native library. Through this I will show you how to create a simple email right through to a more complete email with subject lines, attachments, extended body text and the ability to send to multiple recipients,to achieve more than a simple email we will need in include some additional modules, email.mime.multipart and email.mime.text.
To run the python script on the Pi I am assuming that you have the latest version of Raspian and have the ability to connect to your Pi either through SSH with putty and FTP with filezilla,  or directly with a keyboard and monitor, if you haven’t set-up your Pi yet then check out my getting started section. The code below should work on both python 2.7 and python 3.2 that are used on the Pi.
A further consideration is your internet connection security, given that the scripts below will contain your email address and password in the code it may be wise to consider getting another gmail address or similar just for the purpose of sending automated emails rather than using your normal day to day address and risking it being compromised.

Simple Email:


Warning: Due to Google using oauth 2.0 security normally a 2 stage check is required to access the server, this can be overcome by allowing less secure apps on your account

To send a simple email with no subject line we can use the following code

#!/usr/bin/env python
import smtplib
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(“FromUser@gmail.com“, “FromUserPassword“)
msg = “This is a simple email test!”
server.sendmail(“FromUser@gmail.com“, “ToUser@gmail.com“, msg)
server.quit()

Note: In this example I am using the gmail smtp server, if you are sending from an outlook or yahoo address replace smtp.gmail.com with one of the following:

smtp-mail.outlook.com
smtp.mail.yahoo.com

Replace the entries highlighted in blue with your email address and password and the intended recipient. The msg=” ” is the mesage that will be contained in the body of your email.

Email with a Subject Line:


While a simple email may suffice as an alert just to yourself if you intend the email to look slightly more professional then including a subject line may be important.

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = “FromUser@gmail.com
toaddr = “ToUser@gmail.com
msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
body = ‘This is an extended email test’
msg.attach(MIMEText(body, ‘plain’))
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.ehlo
server.starttls()
server.login(fromaddr, “FromUserPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

Again in this example you just need to enter your details in the blue highlighted entries in the relevant spots in the script, In this case the message in the body of the email is entered in the body=” ” section. The subject line of your email will contain your entry in the  msg [‘Subject’] = ” ”

Email with an Attachment:

To take it one step further if you want to include an attachment with your email the following code can be used.

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = “FromUser@gmail.com
toaddr = “ToUser@gmail.com
msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”body = ‘This is an extended email test’
msg.attach(MIMEText(body, ‘plain’))
filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)
part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

In addition to adding your own information you need to set the name of the file to attach with it’s extension  (eg. testfile.txt) and the full path to where the file can be found (eg. /home/pi/testfile.txt).

Email with Extended Body Text:


If you need to send an email with more text in the body where it is impractical to write it directly into the python code then a text file can be created with the body of the email and then read into the script.

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = “FromUser@gmail.com
toaddr = “ToUser@gmail.com
msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))
filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)
part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

Here you need to add the full path name of the text file containing your body text to the line f = open(” “) eg. /home/pi/email_body_text.txt.

Email with Multiple Recipients:


Finally if you want to send the email to more than one recipient we need to present the all the receiving email addresses to the server.sendmail function.

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = “FromUser@gmail.com
toaddr = “ToUser1@gmail.com,ToUser2@gmail.com,ToUser3@gmail.com
alladdr = toaddr.split(“,”)
msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))
filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)
part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, alladdr, text)
server.quit()

When entering your own information the “toaddr” variable is now where you can add the comma separated recipients. As a bonus if you want to add Cc or Bcc recipients then you will need to add the “ccaddr” and “bccaddr” variables and configure the “alladdr” variable to combine all the intended recipients into one string as show in the code below.

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = “FromUser@gmail.com
toaddr = “ToUser1@gmail.com,ToUser2@gmail.com
ccaddr = “ToUser3@gmail.com,ToUser4@gmail.com,ToUser5@gmail.com
bccaddr = “ToUser6@gmail.com
alladdr = toaddr.split(“,”) + ccaddr.split(“,”) + [bccaddr]msg = MIMEMultipart()
msg[‘From’] = fromaddr
msg[‘To’] = toaddr
msg[‘Subject’] = “Test Alert”
f = open(“PathToEmailBodyTextWithExtension“)
body = f.read()
msg.attach(MIMEText(body, ‘plain’))
filename = “AttachmentFileWithExt
attachment = open(“FullPathToFile“, “rb”)
part = MIMEBase(‘application’, ‘octet-stream’)
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header(‘Content-Disposition’, “attachment; filename= %s” % filename)
msg.attach(part)
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(fromaddr, “FromUserEmailPassword“)
text = msg.as_string()
server.sendmail(fromaddr, alladdr, text)
server.quit()

With these scripts you will now be able to send emails in whatever style you like be that formal or just a simple alert. All the python code for the above emails is available for both 2.x and 3.x on MyHydropi Github Repository.

If you have any thought’s about this article, improvements or errors let me know in the comments below and if you found this helpful, why not share it with others.

Send Email And Receive Email By Raspberry Python Reviewed by Jacky Le on February 23, 2017 Rating: 5

No comments:

All Rights Reserved by JackyLe © 2018 © 2017
Edit bởi: Jacky Le | Youtube Channel: JACKY LE

Send email form

Name

Email *

Message *

Powered by Blogger.