Экспорт (0) Печать
Развернуть все
Эта тема еще не получила оценку - Оценить эту тему

How to Send Email Using SendGrid from Java in a Windows Azure Deployment

Обновлено: Январь 2014 г.

The following example shows you how you can use SendGrid to send emails from a web page hosted in Windows Azure. The resulting application will prompt the user for email values, as shown in the following screen shot.

Формат адреса электронной почты

The resulting email will look similar to the following screen shot.

Сообщение электронной почты

You’ll need to do the following to use the code in this topic:

  1. Obtain the javax.mail JARs, for example from http://www.oracle.com/technetwork/java/javamail/index.html.

  2. Add the JARs to your Java build path.

  3. If you are using Eclipse to create this Java application, you can include the SendGrid libraries in your application deployment file (WAR) using Eclipse’s deployment assembly feature. If you are not using Eclipse to create this Java application, ensure the libraries are included within the same Azure role as your Java application, and added to the class path of your application.

You must also have your own SendGrid username and password, to be able to send the email. To get started with SendGrid, evaluate pricing and sign up at http://sendgrid.com/pricing.html. Windows Azure customers receive a special offer of 25,000 free emails per month from SendGrid. To sign-up for this offer, or get more information, please visit http://www.sendgrid.com/azure.html. For more detailed information on the signup process, see the SendGrid documentation at http://docs.sendgrid.com/documentation/get-started/. For information about additional services provided by SendGrid, see http://sendgrid.com/features.

Additionally, familiarity with the information at Creating a Hello World Application for Windows Azure in Eclipse, or with other techniques for hosting Java applications in Windows Azure if you are not using Eclipse, is highly recommended.

Create a web form for sending email

The following code shows how to create a web form to retrieve user data for sending email. For purposes of this content, the JSP file is named emailform.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email form</title>
 <p>Fill in all fields and click <b>Send this email</b>.</p>
  <form action="sendemail.jsp" method="post">
       <td><input type="text" size=50 name="emailTo">
       <td><input type="text" size=50 name="emailFrom">
       <td><input type="text" size=100 name="emailSubject" value="My email subject">
       <td><input type="text" size=400 name="emailText" value="Hello,<p>This is my message.</p>Thank you." />
       <td>SendGrid user name:</td>
       <td><input type="text" name="sendGridUser">
       <td>SendGrid password:</td>
       <td><input type="password" name="sendGridPassword">
       <td colspan=2><input type="submit" value="Send this email">

Create the code to send the email

The following code, which is called when you complete the form in emailform.jsp, creates the email message and sends it. For purposes of this content, the JSP file is named sendemail.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="javax.activation.*, javax.mail.*, javax.mail.internet.*, java.util.Date, java.util.Properties" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email processing happens here</title>
    <b>This is my send mail page.</b><p/>
 final String sendGridUser = request.getParameter("sendGridUser");
 final String sendGridPassword = request.getParameter("sendGridPassword");
 class SMTPAuthenticator extends Authenticator
   public PasswordAuthentication getPasswordAuthentication()
        String username = sendGridUser;
        String password = sendGridPassword;
        return new PasswordAuthentication(username, password);   
     // The SendGrid SMTP server.
     String SMTP_HOST_NAME = "smtp.sendgrid.net";

     Properties properties;
     properties = new Properties();
     // Specify SMTP values.
     properties.put("mail.transport.protocol", "smtp");
     properties.put("mail.smtp.host", SMTP_HOST_NAME);
     properties.put("mail.smtp.port", 587);
     properties.put("mail.smtp.auth", "true");
     // Display the email fields entered by the user. 
     out.println("Value entered for email Subject: " + request.getParameter("emailSubject") + "<br/>");        
     out.println("Value entered for email      To: " + request.getParameter("emailTo") + "<br/>");
     out.println("Value entered for email    From: " + request.getParameter("emailFrom") + "<br/>");
     out.println("Value entered for email    Text: " + "<br/>" + request.getParameter("emailText") + "<br/>");

     // Create the authenticator object.
     Authenticator authenticator = new SMTPAuthenticator();
     // Create the mail session object.
     Session mailSession;
     mailSession = Session.getDefaultInstance(properties, authenticator);
     // Display debug information to stdout, useful when using the
     // compute emulator during development.

     // Create the message and message part objects.
     MimeMessage message;
     Multipart multipart;
     MimeBodyPart messagePart; 
     message = new MimeMessage(mailSession);
     multipart = new MimeMultipart("alternative");
     messagePart = new MimeBodyPart();
     messagePart.setContent(request.getParameter("emailText"), "text/html");

     // Specify the email To, From, Subject and Content. 
     message.setFrom(new InternetAddress(request.getParameter("emailFrom")));
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(request.getParameter("emailTo")));
     // Uncomment the following if you want to add a footer.
     // message.addHeader("X-SMTPAPI", "{\"filters\": {\"footer\": {\"settings\": {\"enable\":1,\"text/html\": \"<html>This is my <b>email footer</b>.</html>\"}}}}");

     // Uncomment the following if you want to enable click tracking.
     // message.addHeader("X-SMTPAPI", "{\"filters\": {\"clicktrack\": {\"settings\": {\"enable\":1}}}}");
     Transport transport;
     transport = mailSession.getTransport();
     // Connect the transport object.
     // Send the message.
     transport.sendMessage(message,  message.getRecipients(Message.RecipientType.TO));
     // Close the connection.
    out.println("<p>Email processing completed.</p>");
 catch (Exception e)
     out.println("<p>Exception encountered: " + 
                        e.getMessage()     +


In addition to sending the email, emailform.jsp provides a result for the user; an example is the following screen shot:

Результат отправки почты

Next steps

Deploy your application to the compute emulator and within a browser run emailform.jsp, enter values in the form, click Send this email, and then see results in sendemail.jsp.

This code was provided to show you how to use SendGrid in Java on Windows Azure. Before deploying to Windows Azure in production, you may want to add more error handling or other features. For example:

См. также

Другие ресурсы

How to Send Email Using SendGrid from Java

Была ли вам полезна эта информация?
(1500 символов осталось)
Спасибо за ваш отзыв
© 2014 Microsoft. Все права защищены.