SendGrid API and usage in Rails

Tram Ho

Introduce

1. What is SendGrid?

SendGrid is one of the leading Email Marketing service providers in the world. Besides, their free SMTP Server service is also widely used and appreciated. Usually, when using WordPress or other source code, we always use the SMTP information of Hosting to send mail notification. However, because IP Hosting is shared with hundreds of other websites, there is a very high chance of being blacklisted, sending mail sent to Spam. Even worse, some providers even block sending mail to protect the server, if you do not pay attention you will not be able to know this information. When using a dedicated SMTP Server, you will limit this limit, send mail faster, go to standard Inbox without getting lost in Spam. Previously, SendGrid allowed to use completely free with a limit of 12,000 emails / month but for now we can only try FREE for 1 month only. Send up to 40,000 emails within the first 30 days. After that, the fee per month will be 9.95 $, depending on the number of emails you want to send. With the stable quality and high delivery capacity of SendGrid, it is trusted by many large bloggers and businesses.

2. Register for SendGrid account and API key

  • You can refer to this link , quite detailed and clear
  • Following the steps above we will have an API to continue the next steps

3. Create the mailer lib

  • Currently SendGrid has supported gem can import it into the project, you can refer here using Link
  • But for easy understanding and fast I will guide you to build a small mailer lib, use cURL to call the SendGrid v3 API.
  • First initialize a lib:
    • path: /lib/send_grid_mailer.rb
    • You remember to autoload lib config in application.rb, if you do not know, see here
  • Let’s start coding

The parameters passed to lib include : subject,: from,: to,: message_text,: message_html

  • subject: Is the subject of the email that I want to send.
  • from: Sender’s email address, exp: ” [email protected] “.
  • to: The recipient’s mail address, exp: ” [email protected] “.
  • message_text: The content of the email to be sent in text format
  • message_html: Email content can be sent as html code.

In the above code, I have used the variable proxy , which is a variable of HTTPClient, you can see more here if you want to know more.

and variable api_key = “SG.xxxxx” is the api_key provided by SendGrid when creating account. Finally, how to call it out:

Remember to pass all the parameters you guys =)))

4. Conclusion

The above is one of the many ways you can use SendGrid, which is also a convenient and quick and easy way to learn for beginners.

I wish you success =))))

Document link:

Share the news now

Source : Viblo