官术网_书友最值得收藏!

Sending e-mails using Gmail's SMTP server

It does not matter if you are building your company website, an application that will be used only inside the company you work at, or an e-commerce solution. Eventually, you will need to send e-mails. It is fair to say that every web application has the need, at some point, to send e-mails.

In this recipe, we will learn how to send plain text e-mails using Gmail's SMTP server.

Getting ready

You can use the code of the examples we have used in the previous recipe, or you can start a new project.

How to do it...

Carry out the following steps:

  1. You will need to add the following properties into src/main/resources/default.props:
    mail.user=your_email@gmail.com
    mail.password=your_password
  2. Change the mail.user and mail.password properties to match your Gmail account.
  3. Then create a method in the Boot class to configure the Mailer object as follows:
    def configureMailer() {
      import javax.mail{PasswordAuthentication, Authenticator}
      
      System.setProperty("mail.smtp.starttls.enable", "true")
      System.setProperty("mail.smtp.ssl.enable", "true")
      System.setProperty("mail.smtp.host", "smtp.gmail.com")
      System.setProperty("mail.smtp.auth", "true")
      
      Mailer.authenticator = for {
        user <- Props.get("mail.user")
        pass <- Props.get("mail.password")
      } yield new Authenticator {
        override def getPasswordAuthentication =
        new PasswordAuthentication(user, pass)
      }
    }
  4. Then, you need to call the configureMailer method from within the boot method:
    def boot {
      // where to search snippet
      LiftRules.addToPackages("code")
      
      configureMailer()
      ….
    }

    Now, we have the Mailer object configured, and we are ready to send e-mails.

  5. Inside the lib package src/main/scala/code/, create an object called SendEmail that will be responsible for sending e-mails:
    import net.liftweb.util.Mailer
    import net.liftweb.util.Mailer._
    
    object SendEmail {
      def send_!(from: String,
        recipient: String,
        subject: String,
      body: String) {
        val mailTypes = List(PlainMailBodyType(body), To(recipient))
        
        Mailer.msgSendImpl (
          From(from),
          Subject(subject),
        mailTypes)
      }
    }
  6. At last, we will create a snippet to render a link to send e-mails when clicked. For this, you will need to create a class called EmailSnippet inside the snippet package, src/main/scala/code/:
    import net.liftweb.http.SHtml
    import net.liftweb.util. Helpers._
    import code.lib.SendEmail
    import xml.Text
    import net.liftweb.util.Props
    
    class SEmail {
      def sendNow() = {
        SendEmail.send_!(
          Props.get("mail.user").get,
          "to_email@example.com",
          "Sending e-mail using GMail",
          "Here is the body content."
        )
      }
      
      def sendEmail = {
        "*" #> SHtml.link("#", () => sendNow(), Text("Send e-mail"))
      }
    }
  7. Change to_email@example.com to match your Gmail account.
  8. You will also need to create the following menu item in the entries list, just after the index entry:
    Menu.i("Send Email") / "send"
  9. Create a file called send.html inside src/main/webapp as follows:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
        <title>Home</title>
      </head>
      <body class="lift:content_id=main">
        <div id="main" class="lift:surround?with=default;at=content">
        <h2>Sending e-mail using GMail's SMTP server.</h2>
        
        <p>
          <span data-lift="EmailSnippet.sendEmail"><!-- there will be a button here --></span>
        </p>
        </div>
      </body>
    </html>
  10. Start the application and go to http://localhost:8080/send.

    You should see a page containing a link called Send e-mail, similar to the following screenshot:

  11. Click on the link to send the email, and you will receive an email in your Gmail inbox.

How it works...

First of all, we have set a few mail properties that will be used by the Java Mail API, such as mail.smtp.ssl.enable and mail.smtp.starttls.enable. These properties will enable SSL and TLS, meaning that we will use a secure channel to send the e-mail, and mail.smtp.host to set the SMTP server address. Then, we set mail.smtp.auth to true to use the SMTP authentication.

The next thing we did was to create an authenticator to use the Mailer object.

Note

Mailer is a built-in Lift object that contains utilities to send e-mails.

When creating the authenticator, we used the Props object to get the user and password values from the default.props file.

Note

Props is a Lift helper object that can be used to get values from properties files.

Then, we created the EmailSnippet class that creates a link which when clicked, invokes the sendNow() method. This method has no parameters and calls the SendEmail's send_! method, passing information such as from, to, subject, and body that will be used to send the e-mail. We had to wrap the call to send_! to keep the code easy to read. Then SendEmail's send_! invokes Mailer object's sendMail method, which is the method that will send the e-mail.

There's more...

Why did we do all of this in the Boot class? Well, we just needed to configure the Mailer object once. This is because it's a singleton, which means that only one instance of the object will be created, and we can use it throughout the application once it is configured. So, Boot is the perfect place to do this, since it is called only once when the server, in our case Jetty, is starting the application.

Note that we configured the Mailer object in a programmatic way. However, if you want to use The Java Naming and Directory Interface (JNDI) to configure the Mailer object, you will need to do two things.

Note

By using JNDI to configure the Mailer object, you can rely on the fact that the configurations will be set on the server; your application only needs to know the JNDI name to be able to use a given resource. This means that if you need to change the application server where your application will run, you won't have problems with different settings causing your application to break.

  1. First you need to call the following code instead of using the configureMailer() method:
    Mailer.jndiName = Full("mail/Session")
  2. Second, you need to configure the server to provide a mail session via JNDI. You do this by creating a file called jetty-env.xml inside the WEB-INF folder:
    <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
    <Configure class="org.eclipse.jetty.webapp.WebAppContext">
      <New id="mail" class="org.eclipse.jetty.plus.jndi.Resource">
        <Arg>mail/Session</Arg>
        <Arg>
          <New class="org.eclipse.jetty.jndi.factories.MailSessionReference">
            <Set name="user">your_email@gmail.com</Set>
            <Set name="password">your_password</Set>
            <Set name="properties">
              <New class="java.util.Properties">
                <Put name="mail.transport.protocol">smtp</Put>
                <Put name="mail.smtp.host">smtp.gmail.com</Put>
                <Put name="mail.smtp.auth">true</Put>
                <Put name="mail.smtp.starttls.enable">true</Put>
                <Put name="mail.smtp.ssl.enable">true</Put>
                <Put name="mail.debug">true</Put>
              </New>
            </Set>
          </New>
        </Arg>
      </New>
    </Configure>

See also

You can get more information about the Mailer objects at the following addresses:

主站蜘蛛池模板: 东方市| 荆门市| 开远市| 沈丘县| 瓮安县| 麻栗坡县| 太仆寺旗| 获嘉县| 廉江市| 当雄县| 剑河县| 久治县| 井陉县| 井陉县| 陇南市| 曲麻莱县| 安塞县| 华坪县| 湘潭市| 海宁市| 德化县| 拜泉县| 金川县| 平度市| 望奎县| 类乌齐县| 清远市| 和龙市| 莎车县| 浦江县| 宕昌县| 塔河县| 通江县| 保定市| 沁阳市| 青海省| 上饶市| 利津县| 德钦县| 尚义县| 满洲里市|