/articles/store-sendgrid-nodejs-how-to-send-email.md

https://github.com/tlotter/azure-content · Markdown · 287 lines · 219 code · 68 blank · 0 comment · 0 complexity · e7969f4fbe7acdf3411353bd66b04eaa MD5 · raw file

  1. <properties linkid="dev-nodejs-how-to-sendgrid-email-service" urlDisplayName="SendGrid Email Service" pageTitle="How to use the SendGrid email service (Node.js) - Azure" metaKeywords="Azure SendGrid, Azure email service, Azure SendGrid Node.js, Azure email Node.js" description="Learn how send email with the SendGrid email service on Azure. Code samples written using the Node.js API." metaCanonical="" services="" documentationCenter="Node.js" title="How to Send Email Using SendGrid from Node.js" authors="" solutions="" manager="" editor="" />
  2. # How to Send Email Using SendGrid from Node.js
  3. This guide demonstrates how to perform common programming tasks with the
  4. SendGrid email service on Azure. The samples are written using
  5. the Node.js API. The scenarios covered include **constructing email**,
  6. **sending email**, **adding attachments**, **using filters**, and
  7. **updating properties**. For more information on SendGrid and sending
  8. email, see the [Next Steps][] section.
  9. ## Table of Contents
  10. * [What is the SendGrid Email Service?][]
  11. * [Create a SendGrid Account][]
  12. * [Reference the SendGrid Node.js Module][]
  13. * [How to: Create an Email][]
  14. * [How to: Send an Email][]
  15. * [How to: Add an Attachment][]
  16. * [How to: Use Filters to Enable Footers, Tracking, and Analytics][]
  17. * [How to: Update Email Properties][]
  18. * [How to: Use Additional SendGrid Services][]
  19. * [Next Steps][1]
  20. ## <a name="whatis"> </a>What is the SendGrid Email Service?
  21. SendGrid is a [cloud-based email service] that provides reliable
  22. [transactional email delivery], scalability, and real-time analytics along with flexible APIs
  23. that make custom integration easy. Common SendGrid usage scenarios
  24. include:
  25. - Automatically sending receipts to customers
  26. - Administering distribution lists for sending customers monthly
  27. e-fliers and special offers
  28. - Collecting real-time metrics for things like blocked e-mail, and
  29. customer responsiveness
  30. - Generating reports to help identify trends
  31. - Forwarding customer inquiries
  32. - Email notifications from your application
  33. For more information, see [http://sendgrid.com](http://sendgrid.com).
  34. ## <a name="createaccount"> </a>Create a SendGrid Account
  35. [WACOM.INCLUDE [sendgrid-sign-up](../includes/sendgrid-sign-up.md)]
  36. ## <a name="reference"> </a>Reference the SendGrid Node.js Module
  37. The SendGrid module for Node.js can be installed through the node
  38. package manager (npm) by using the following command:
  39. npm install sendgrid
  40. After installation, you can require the module in your application by
  41. using the following code:
  42. var SendGrid = require('sendgrid')
  43. The SendGrid module exports the **SendGrid** and **Email** functions.
  44. **SendGrid** is responsible for sending email through either SMTP or Web
  45. API, while **Email** encapsulates an email message.
  46. ## <a name="createemail"> </a>How to: Create an Email
  47. Creating an email message using the SendGrid module involves first
  48. creating an email message using the Email function, and then sending it
  49. using the SendGrid function. The following is an example of creating a
  50. new message using the Email function:
  51. var mail = new SendGrid.Email({
  52. to: 'john@contoso.com',
  53. from: 'anna@contoso.com',
  54. subject: 'test mail',
  55. text: 'This is a sample email message.'
  56. });
  57. You can also specify an HTML message for clients that support it by
  58. setting the html property. For example:
  59. html: This is a sample <b>HTML<b> email message.
  60. Setting both the text and html properties provides graceful fallback to
  61. text content for clients that cannot support HTML messages.
  62. For more information on all properties supported by the Email function,
  63. see [sendgrid-nodejs][].
  64. ## <a name="sendemail"> </a>How to: Send an Email
  65. After creating an email message using the Email function, you can send
  66. it using either SMTP or the Web API provided by SendGrid. For details
  67. about the benefits and differences of each API, see [SMTP vs. Web API][]
  68. in the SendGrid documentation.
  69. Using either the SMTP API or Web API requires that you first initialize
  70. the SendGrid function using the user and key of your SendGrid account as
  71. follows:
  72. var sender = new SendGrid('user','key');
  73. The message can now be sent using either SMTP or the Web API. The calls
  74. are virtually identical, passing the email message and an optional
  75. callback function; The callback is used to determine the success or
  76. failure of the operation. The following examples show how to send a
  77. message using both SMTP and the Web API.
  78. ### SMTP
  79. sender.smtp(mail, function(success, err){
  80. if(success) console.log('Email sent');
  81. else console.log(err);
  82. });
  83. ### Web API
  84. sender.send(mail, function(success, err){
  85. if(success) console.log('Email sent');
  86. else console.log(err);
  87. });
  88. <div class="dev-callout">
  89. <strong>Note</strong>
  90. <p>While the above examples show passing in an email object and
  91. callback function, you can also directly invoke the send and smtp
  92. functions by directly specifying email properties. For example:</p>
  93. <pre class="prettyprint">sender.send({
  94. to: 'john@contoso.com',
  95. from: 'anna@contoso.com',
  96. subject: 'test mail',
  97. text: 'This is a sample email message.'
  98. });
  99. </pre>
  100. </div>
  101. ## <a name="addattachment"> </a>How to: Add an Attachment
  102. Attachments can be added to a message by specifying the file name(s) and
  103. path(s) in the **files** property. The following example demonstrates
  104. sending an attachment:
  105. sender.send({
  106. to: 'john@contoso.com',
  107. from: 'anna@contoso.com',
  108. subject: 'test mail',
  109. text: 'This is a sample email message.',
  110. files: {
  111. 'file1.txt': __dirname + '/file1.txt',
  112. 'image.jpg': __dirname + '/image.jpg'
  113. }
  114. });
  115. <div class="dev-callout">
  116. <strong>Note</strong>
  117. <p>When using the <strong>files</strong> property, the file must be accessible
  118. through <a href="http://nodejs.org/docs/v0.6.7/api/fs.html#fs.readFile">fs.readFile</a>. If the file you wish to attach is hosted in Azure Storage, such as in a Blob container, you must first copy the file to local storage or to an Azure drive before it can be sent as an attachment using the <strong>files</strong> property.</p>
  119. </div>
  120. ## <a name="usefilters"> </a>How to: Use Filters to Enable Footers, Tracking, and Twitter
  121. SendGrid provides additional email functionality through the use of
  122. filters. These are settings that can be added to an email message to
  123. enable specific functionality such as enabling click tracking, Google
  124. analytics, subscription tracking, and so on. For a full list of filters,
  125. see [Filter Settings][].
  126. Filters can be applied to a message by using the **filters** property.
  127. Each filter is specified by a hash containing filter-specific settings.
  128. The following examples demonstrate the footer, click tracking, and
  129. Twitter filters:
  130. ### Footer
  131. sender.send({
  132. to: 'john@contoso.com',
  133. from: 'anna@contoso.com',
  134. subject: 'test mail',
  135. text: 'This is a sample email message.',
  136. filters: {
  137. 'footer': {
  138. 'settings': {
  139. 'enable': 1,
  140. 'text/plain': 'This is a text footer.'
  141. }
  142. }
  143. }
  144. });
  145. ### Click Tracking
  146. sender.send({
  147. to: 'john@contoso.com',
  148. from: 'anna@contoso.com',
  149. subject: 'test mail',
  150. text: 'This is a sample email message.',
  151. filters: {
  152. 'clicktrack': {
  153. 'settings': {
  154. 'enable': 1
  155. }
  156. }
  157. }
  158. });
  159. ### Twitter
  160. sender.send({
  161. to: 'john@contoso.com',
  162. from: 'anna@contoso.com',
  163. subject: 'test mail',
  164. text: 'This is a sample email message.',
  165. filters: {
  166. 'twitter': {
  167. 'settings': {
  168. 'enable': 1,
  169. 'username': 'twitter_username',
  170. 'password': 'twitter_password'
  171. }
  172. }
  173. }
  174. });
  175. ## <a name="updateproperties"> </a>How to: Update Email Properties
  176. Some email properties can be overwritten using **set*Property*** or
  177. appended using **add*Property***. For example, you can add additional
  178. recipients by using
  179. email.addTo('jeff@contoso.com');
  180. or set a filter by using
  181. email.setFilterSetting({
  182. 'footer': {
  183. 'setting': {
  184. 'enable': 1,
  185. 'text/plain': 'This is a footer.'
  186. }
  187. }
  188. });
  189. For more information, see [sendgrid-nodejs][].
  190. ## <a name="useservices"> </a>How to: Use Additional SendGrid Services
  191. SendGrid offers web-based APIs that you can use to leverage additional
  192. SendGrid functionality from your Azure application. For full
  193. details, see the [SendGrid API documentation][].
  194. ## <a name="nextsteps"> </a>Next Steps
  195. Now that you've learned the basics of the SendGrid Email service, follow
  196. these links to learn more.
  197. - SendGrid Node.js module repository: [sendgrid-nodejs][]
  198. - SendGrid API documentation:
  199. <http://docs.sendgrid.com/documentation/api/>
  200. - SendGrid special offer for Azure customers:
  201. [http://sendgrid.com/azure.html](http://sendgrid.com/azure.html)
  202. [Next Steps]: http://www.windowsazure.com/en-us/develop/nodejs/how-to-guides/blob-storage/#next-steps
  203. [What is the SendGrid Email Service?]: #whatis
  204. [Create a SendGrid Account]: #createaccount
  205. [Reference the SendGrid Node.js Module]: #reference
  206. [How to: Create an Email]: #createemail
  207. [How to: Send an Email]: #sendemail
  208. [How to: Add an Attachment]: #addattachment
  209. [How to: Use Filters to Enable Footers, Tracking, and Analytics]: #usefilters
  210. [How to: Update Email Properties]: #updateproperties
  211. [How to: Use Additional SendGrid Services]: #useservices
  212. [1]: #nextsteps
  213. [special offer]: http://www.sendgrid.com/azure.html
  214. [sendgrid-nodejs]: https://github.com/sendgrid/sendgrid-nodejs
  215. [SMTP vs. Web API]: http://docs.sendgrid.com/documentation/get-started/integrate/examples/smtp-vs-rest/
  216. [Filter Settings]: http://docs.sendgrid.com/documentation/api/smtp-api/filter-settings/
  217. [SendGrid API documentation]: http://docs.sendgrid.com/documentation/api/
  218. [cloud-based email service]: http://sendgrid.com/solutions
  219. [transactional email delivery]: http://sendgrid.com/transactional-email