- Lift Application Development Cookbook
- Gilberto T. Garcia Jr.
- 721字
- 2021-08-04 10:05:43
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:
- You will need to add the following properties into
src/main/resources/default.props
:mail.user=your_email@gmail.com mail.password=your_password
- Change the
mail.user
andmail.password
properties to match your Gmail account. - Then create a method in the
Boot
class to configure theMailer
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) } }
- Then, you need to call the
configureMailer
method from within theboot
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. - Inside the lib package
src/main/scala/code/
, create an object calledSendEmail
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) } }
- 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")) } }
- Change
to_email@example.com
to match your Gmail account. - You will also need to create the following menu item in the entries list, just after the index entry:
Menu.i("Send Email") / "send"
- Create a file called
send.html
insidesrc/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>
- 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:
- 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.
- First you need to call the following code instead of using the
configureMailer()
method:Mailer.jndiName = Full("mail/Session")
- 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 theWEB-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:
- 技術(shù)領(lǐng)導(dǎo)力:程序員如何才能帶團(tuán)隊(duì)
- Responsive Web Design with HTML5 and CSS3
- C語言程序設(shè)計(jì)立體化案例教程
- Java Web開發(fā)技術(shù)教程
- 零基礎(chǔ)學(xué)Python數(shù)據(jù)分析(升級(jí)版)
- Java EE 7 Performance Tuning and Optimization
- Instant Nancy Web Development
- Angular開發(fā)入門與實(shí)戰(zhàn)
- Keras深度學(xué)習(xí)實(shí)戰(zhàn)
- Scala for Machine Learning(Second Edition)
- Emgu CV Essentials
- Go語言編程
- 計(jì)算語言學(xué)導(dǎo)論
- 軟件測(cè)試技術(shù)
- Selenium自動(dòng)化測(cè)試實(shí)戰(zhàn):基于Python