How to Read a Mime Message in Console

Updated on May 6, 2020

Gmail is one of the near pop e-mail services so far, and you lot will very probably want to use it as a mailbox for your web or mobile app. It is safe and credible, which is crucial to foreclose your emails from going into the spam folder. That'due south why nosotros decided to mankind out how to send emails with Gmail API.

Gmail API – why you should consider using information technology

The API provides y'all with a RESTful admission to the features you ordinarily have with Gmail:

  • Send and receive HTML emails
  • Send and receive emails with attachments
  • Crud (create, read, update, and delete) operations with messages, drafts, threads, and labels
  • Admission control of your Gmail inbox
  • Full search capabilities of the web UI
  • Perform specific queries
  • And many more…

Developers dear Gmail API because it'southward like shooting fish in a barrel to implement. Nosotros'll talk about that a bit later. Likewise, yous tin can use this selection for versatile cases like:

  • automated email sending
  • mail fill-in
  • postal service migration from other email services

Resource types and methods

With Gmail API, you can deal with several resource types and manage them using the following methods:

Resource type Method
Typhoon
an unsent message that you tin can modify once created
  • create (creating a new draft)
  • delete (removing the specified typhoon)
  • get (obtaining the specified draft)
  • list (listing drafts in the mailbox)
  • send (sending the specified draft according to the To, Cc, and Bcc headers)
  • update (updating the specified draft'southward content)
  • Bulletin
    an immutable resource that you cannot change
  • batchDelete (removing messages past message ID)
  • batchModify (modifying labels on the specified letters)
  • delete (removing the specified message)
  • become (obtaining the specified message)
  • import (importing the message into the mailbox (similar to receiving via SMTP))
  • insert (inserting the message into the mailbox (similar to IMAP)
  • listing (listing messages in the mailbox)
  • modify (modifying labels on the specified bulletin)
  • send (sending the specified message according to the To, Cc, and Bcc headers)
  • trash (transferring the specified message to the trash)
  • untrash (transferring the specified message from the trash)
  • Thread
    a drove of messages within a single conversation
  • delete (removing the specified thread)
  • get (obtaining the specified thread)
  • list (listing threads in the mailbox)
  • modify (modifying labels in the thread)
  • trash (transferring the specified thread to the trash)
  • untrash (transferring the specified thread from the trash)
  • Label
    a resource to organize messages and threads (for example, inbox, spam, trash, etc.)
  • create (creating a new label)
  • delete (removing the specified characterization)
  • get (obtaining the specified characterization)
  • list (listing labels in the mailbox)
  • patch (patching the specified label) – this method supports patch semantics
  • update (updating the specified label).
  • History
    a collection of changes fabricated to the mailbox
  • list (listing the history of all changes to the mailbox)
  • Settings
    setting up Gmail features
  • getAutoForwarding (auto-forwarding setting)
  • updateAutoForwarding (updating the auto-forwarding setting)
  • getImap (IMAP settings)
  • updateImap (updating IMAP settings)
  • getLanguage (language settings)
  • updateLanguage (updating language settings)
  • getPop (POP3 settings)
  • updatePop (updating POP3 settings)
  • getVacation (vacation responder settings)
  • updateVacation (updating vacation responder settings)
  • How to make your app send emails with Gmail API

    Step ane: Create a project at Google API Panel

    If you desire to have access to your Gmail from your mobile or web app, you should start with Google Developers Panel. Those who visit this page for the commencement time always will take to concord with the Terms of Service and pick their Country of residence. Then click Select a project and create a new one.

    Name your new project and press Create at the lesser.

    Stride 2: Enable Gmail API

    Once that's done, you can printing the Library tab on the left and find yourself in the API Library folio. Enter "Gmail API" in the search bar and click on information technology once constitute. At present, you demand to enable the API for your project.

    Note that yous'll have to enable it separately for each new project y'all work on.

    Step 3: Credentials and authentication with OAuth 2.0

    Once the API is enabled, yous'll be taken to a overnice dashboard that says, "To use this API, you may need credentials". If you click Create credentials, yous'll have to laissez passer through a set of questions to find out what kind of credentials y'all demand. Nosotros propose you to get another way since nosotros already know what it is: OAuth client ID. Then, click the Credential tab on the left, and so selection OAuth customer ID from the drop-down list of the Create Credentials push.

    You'll see the Configure consent screen button. It volition bring yous to a page with many fields. You can only enter the proper name of your app and specify authorized domains. Fill in other fields if you want.

    Click salvage and so pick the type of your app (spider web app, Android, Chrome App, iOS, or other). After that, name your OAuth Customer ID. Also, enter JavaScript origins and redirect domains for use with requests from a browser or a web server respectively. Click create to finalize. That'south it. Download a JSON file with your credentials – you'll demand it later on.

    Footstep 4: Choice a quickstart guide

    The next stride is to select a quickstart guide according to the applied science your app is built with. So far, there are the following options:

    • API for Go
    • API for Java
    • API for Cerise
    • API for .NET
    • API for Node.js
    • API for PHP
    • API for Python
    • API for browser (JavaScript)

    For mobile apps, there are G Suite APIs for iOS and Android every bit well.

    What yous need first in this quickstart guide is the Prerequisites department. Allow'due south say your choice is PHP. In this instance, make certain your PHP version corresponds to the given 1. As well, install the JSON extension and the Composer dependency management tool if you haven't already. Afterwards that, y'all can install the Google Client Library. For Java, you'll need to create a new project construction and the src/master/resources/ directory. Then, copy the JSON file with credentials to this directory and replace the content of the build.gradle file with this code. So, pay attention when preparing your project.

    Route your test emails to Mailtrap for safe testing.

    Step five: API client library

    Google provides client libraries to work with the API:

    API client for Go

              Installation: go go -u google.golang.org/api/gmail/v1 get get -u golang.org/x/oauth2/google        

    API client for Java

              Installation via Gradle  repositories {        mavenCentral()    }    dependencies {        compile 'com.google.api-client:google-api-client:1.30.two'     }        

    API customer for Ruby-red

              Installation: gem install google-api-client        

    API customer for .NET

              Installation via NuGet Parcel Manager Panel: Install-Parcel Google.Apis.Gmail.v1        

    API client for Node.js

              Installation via npm: npm install googleapis@39 --salvage        

    API client for PHP

              Installation via Composer: composer require google/apiclient:"^two.0"        

    API customer for Python

              Installation: pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib or easy_install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib        

    Step 6: Access to Gmail

    In this step, we demand to authorize access to your Gmail business relationship from the app, and then you'll be able to manage emails. For this, you lot need to create a file in your working directory. Below you'll find the specific file names for each technology. Copy-paste a corresponding lawmaking sample from the chosen Quickstart Guide and run information technology. Here are the links to the code samples:

    Go

    • Filename: quickstart.go
    • Directory: gmail/quickstart/
    • Code sample for Get
    • Run with: become run quickstart.become

    Java

    • Flinename: GmailQuickstart.coffee
    • Directory: src/main/java/
    • Code sample for Coffee
    • Run with: gradle run

    Cherry-red

    • Filename: quickstart.rb
    • Directory: gmail/quickstart/
    • Code sample for Scarlet
    • Run with: ruby quickstart.rb

    .Internet

    • Filename: GmailQuickstart.cs
    • Directory: gmail/GmailQuickstart/
    • Code sample for .NET
    • Run by clicking Start in the Visual Studio toolbar

    Node.js

    • Filename: index.js
    • Directory: gmail/quickstart/
    • Code sample for Node.js
    • Run with: node .

    PHP

    • Filename: quickstart.php
    • Directory: gmail/quickstart/
    • Lawmaking sample for PHP
    • Run with: php quickstart.php

    Python

    • Filename: quickstart.py
    • Directory: gmail/quickstart/
    • Lawmaking sample for Python
    • Run with: python quickstart.py

    JavaScript (browser)

    • Filename: index.html
    • Directory: gmail/quickstart/
    • Code sample for browser (JavaScript)
    • Replace <YOUR_CLIENT_ID> with your client ID and <YOUR_API_KEY> with your API primal. Run with:
    • python -thousand SimpleHTTPServer 8000 – for Python 2+
    • python -m http.server 8000 – for Python 3+

    It worked…or not. Google will warn you nigh a likely failure of the sample y'all run to open a new window in your default browser. If this happens, yous'll need to do it manually. Copy the URL from the panel and paste information technology in the browser. It volition await similar this:

    Adjacent, you'll be asked to either log into your Google account or select one business relationship for say-so. Printing allow and you'll see all your inbox labels in the SSH shell like this:

    Congrats! Gmail API works and you tin can send your first email.

    Pace 7: Create an email

    To send a message, kickoff you need to create one. For this, your app can use the drafts.create method which includes:

    • Creation of a MIME message
    • Conversion of the message into a base64url encoded cord
    • Cosmos of a draft

    Allow's come across how this is done in exercise with Python:

              def create_message(sender, to, subject, message_text):   message = MIMEText(message_text)   message['to'] = to   bulletin['from'] = sender   message['subject'] = subject   raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))   return {     'raw': raw_message.decode("utf-viii")   }   def create_draft(service, user_id, message_body):   try:     message = {'message': message_body}     draft = service.users().drafts().create(userId=user_id, body=message).execute()      impress("Draft id: %southward\nDraft message: %south" % (draft['id'], draft['bulletin']))      return draft   except Exception every bit east:     print('An fault occurred: %s' % due east)     render None                  

    and PHP

              /** * @param $sender string sender email address * @param $to string recipient email address * @param $subject area string email subject * @param $messageText string email text * @return Google_Service_Gmail_Message */ part createMessage($sender, $to, $subject, $messageText) {  $message = new Google_Service_Gmail_Message();   $rawMessageString = "From: <{$sender}>\r\n";  $rawMessageString .= "To: <{$to}>\r\due north";  $rawMessageString .= 'Subject: =?utf-eight?B?' . base64_encode($subject) . "?=\r\n";  $rawMessageString .= "MIME-Version: 1.0\r\due north";  $rawMessageString .= "Content-Type: text/html; charset=utf-viii\r\n";  $rawMessageString .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";  $rawMessageString .= "{$messageText}\r\northward";   $rawMessage = strtr(base64_encode($rawMessageString), array('+' => '-', '/' => '_'));  $message->setRaw($rawMessage);  render $message; }    /** * @param $service Google_Service_Gmail an authorized Gmail API service instance. * @param $user cord User's electronic mail accost or "me" * @param $message Google_Service_Gmail_Message * @render Google_Service_Gmail_Draft */ function createDraft($service, $user, $bulletin) {  $draft = new Google_Service_Gmail_Draft();  $draft->setMessage($message);   endeavour {    $typhoon = $service->users_drafts->create($user, $typhoon);    print 'Draft ID: ' . $draft->getId();  } catch (Exception $e) {    print 'An mistake occurred: ' . $e->getMessage();  }   render $draft; }        

    Test Your Emails Now

    Footstep 8: Send an email

    Once you have created your message, yous can either telephone call messages.send or drafts.send to transport it. Hither is how it may await:

    Python

              def send_message(service, user_id, message):   attempt:     message = service.users().messages().send(userId=user_id, trunk=message).execute()     print('Message Id: %southward' % message['id'])     return message   except Exception as east:     print('An error occurred: %s' % e)     render None        

    and PHP

              /** * @param $service Google_Service_Gmail an authorized Gmail API service instance. * @param $userId string User's e-mail accost or "me" * @param $message Google_Service_Gmail_Message * @render null|Google_Service_Gmail_Message */ role sendMessage($service, $userId, $message) {  try {    $message = $service->users_messages->send($userId, $message);    print 'Message with ID: ' . $bulletin->getId() . ' sent.';    return $bulletin;  } grab (Exception $e) {    impress 'An fault occurred: ' . $e->getMessage();  }   render null; }        

    Stride 8.ane: Send an e-mail with attachments

    You tin also create and ship a multi-part MIME message. For example, this is how it looks with Python:

              def send_message(service, user_id, message):   try:     message = service.users().messages().transport(userId=user_id, body=bulletin).execute()      impress('Message Id: %s' % message['id'])      return message   except Exception every bit e:     impress('An mistake occurred: %s' % e)     render None   def create_message_with_attachment(sender, to, subject field, message_text, file):   bulletin = MIMEMultipart()   message['to'] = to   message['from'] = sender   message['subject'] = subject    msg = MIMEText(message_text)   message.adhere(msg)    content_type, encoding = mimetypes.guess_type(file)    if content_type is None or encoding is non None:     content_type = 'application/octet-stream'    main_type, sub_type = content_type.split('/', 1)    if main_type == 'text':     fp = open(file, 'rb')     msg = MIMEText(fp.read().decode("utf-eight"), _subtype=sub_type)     fp.close()   elif main_type == 'paradigm':     fp = open(file, 'rb')     msg = MIMEImage(fp.read(), _subtype=sub_type)     fp.close()   elif main_type == 'audio':     fp = open(file, 'rb')     msg = MIMEAudio(fp.read(), _subtype=sub_type)     fp.close()   else:     fp = open(file, 'rb')     msg = MIMEBase(main_type, sub_type)     msg.set_payload(fp.read())     fp.close()   filename = os.path.basename(file)   msg.add_header('Content-Disposition', 'attachment', filename=filename)   message.attach(msg)    raw_message = base64.urlsafe_b64encode(message.as_string().encode("utf-8"))   return {'raw': raw_message.decode("utf-eight")}        

    Test your emails earlier they are sent to real users.

    Step 9: Read a specific e-mail from your inbox

    It would be weird if you can't use the API to read letters from Gmail. Luckily you tin can past using the get method past the bulletin ID. Here is how it may look in a Python app:

              import base64 import email  def get_messages(service, user_id):   try:     return service.users().messages().list(userId=user_id).execute()   except Exception as error:     print('An error occurred: %s' % mistake)   def get_message(service, user_id, msg_id):   try:     render service.users().letters().become(userId=user_id, id=msg_id, format='metadata').execute()   except Exception equally fault:     impress('An fault occurred: %s' % fault)   def get_mime_message(service, user_id, msg_id):   try:     message = service.users().letters().get(userId=user_id, id=msg_id,                                              format='raw').execute()     print('Message snippet: %s' % bulletin['snippet'])     msg_str = base64.urlsafe_b64decode(message['raw'].encode("utf-8")).decode("utf-eight")     mime_msg = email.message_from_string(msg_str)      render mime_msg   except Exception as error:     print('An error occurred: %southward' % error)        

    If the message contains an attachment, expand your code with the following:

              def get_attachments(service, user_id, msg_id, store_dir):   endeavor:     message = service.users().messages().get(userId=user_id, id=msg_id).execute()      for part in message['payload']['parts']:       if(part['filename'] and role['body'] and part['body']['attachmentId']):         attachment = service.users().messages().attachments().get(id=function['body']['attachmentId'], userId=user_id, messageId=msg_id).execute()          file_data = base64.urlsafe_b64decode(attachment['information'].encode('utf-8'))         path = ''.bring together([store_dir, part['filename']])          f = open(path, 'wb')         f.write(file_data)         f.close()   except Exception as error:     impress('An fault occurred: %south' % error)        

    Why is Gmail API amend or worse than traditional SMTP?

    E-mail protocol used

    Simple Mail Transfer Protocol (SMTP) is a set of rules for sending emails either from the sender to the email server or betwixt servers. Most email service providers use SMTP to send and POP3/IMAP4 to receive emails. To learn more than about these protocols, you can read our IMAP vs. POP3 vs. SMTP blog post. Google also provides the Gmail SMTP server as a free SMTP service. Awarding Programming Interface (API) is an interaction channel used past apps, platforms, and codes to reach each other. With Gmail API, you tin can transport emails using only HyperText Transfer Protocol (HTTP), a set up of rules that defines how messages are formatted and transmitted.

    How are emails sent?

    You lot can call the API from the app to communicate with an email service that is used to send emails from another server.

    For SMTP, a client establishes a TCP connection to the SMTP server and transfers an email. After dominance, the server sends the email to the recipient'due south SMTP server, which, in turn, forwards it to the IMAP4 or POP3 server. Client and server communicate with each other using SMTP commands and responses.

    Authentication

    Gmail API uses open up authentication (Oauth2), which only lets you request the telescopic of access y'all demand. SMTP provides full access to the account using client login and password SMTP hallmark.

    Quota

    The usage limit of Gmail API is one billion quota units per 24-hour interval. Each method requires a item number of quota units. For example, a drafts.create is ten units and a messages.send is 100 units. Gmail API enforces standard daily mail sending limits. Also, keep in mind that the maximum email size in Gmail is 25MB.

    SMTP or API?

    Each option has its own pros and cons. SMTP is a widely adopted and easy-to-set-upward solution to send emails. Moreover, you don't need any coding skills to handle stuff. Also, you lot can do good from using a fake SMTP server such every bit Mailtrap every bit a playground for safe email testing.

    As well, it is a nifty option to automate processes and provide a wide range of functionality for the app. Also, API tin can avowal an extra level of security, which is crucial if you lot deal with sending sensitive data in emails.

    evansupose1955.blogspot.com

    Source: https://mailtrap.io/blog/send-emails-with-gmail-api/

    0 Response to "How to Read a Mime Message in Console"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel