Using the Java Struts Framework to implement e-mail sending function _java

Source: Internet
Author: User

This chapter will teach you how to use the STRUTS2 application to send e-mail. For this exercise, you need to download and install the Mail.jar from JavaMail API1.4.4, and place Mail.jar files in the Web-inflib folder, and then continue to follow the standard steps to create actions, views, and configuration files.

To create an action:
The next step is to create an action method that sends an e-mail message. Let's create a new class called Emailer.java the following content.

Package com.yiibai.struts2;
Import java.util.Properties;
Import Javax.mail.Message;
Import javax.mail.PasswordAuthentication;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;

Import Javax.mail.internet.MimeMessage;

Import Com.opensymphony.xwork2.ActionSupport;
  public class Emailer extends Actionsupport {private String from;
  private String password;
  Private String to;
  Private String subject;

  Private String body;
  Static Properties Properties = new properties ();
   static {Properties.put ("Mail.smtp.host", "smtp.gmail.com");
   Properties.put ("Mail.smtp.socketFactory.port", "465");
   Properties.put ("Mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   Properties.put ("Mail.smtp.auth", "true");
  Properties.put ("Mail.smtp.port", "465");
   public string Execute () {string ret = SUCCESS; try {Session session = Session.getdefaultinstance (properties, New javax.maIl. Authenticator () {protected passwordauthentication getpasswordauthentication () {Return to new pass
      Wordauthentication (from, password);

     }});
     Message message = new MimeMessage (session);
     Message.setfrom (New InternetAddress (from));
     Message.setrecipients (Message.RecipientType.TO, Internetaddress.parse (to));
     Message.setsubject (subject);
     Message.settext (body);
   Transport.send (message);
     catch (Exception e) {ret = ERROR;
   E.printstacktrace ();
  return ret;
  Public String Getfrom () {return from;
  public void Setfrom (String from) {this.from = from;
  Public String GetPassword () {return password;
  } public void SetPassword (String password) {this.password = password;
  Public String Getto () {return to;
  public void Setto (String to) {this.to = to;
  Public String Getsubject () {return subject;
  } public void Setsubject (String subject) { This.subject = subject;
  Public String GetBody () {return body;
  public void Setbody (String body) {this.body = body;
  public static Properties GetProperties () {return properties;
  public static void SetProperties (Properties properties) {Emailer.properties = properties;

 }
}

You can see in the source code above that Emailer.java has the corresponding form of the properties of the email.jsp page given below. These properties

    • From-Sender's e-mail address. Since we are using Google's SMTP, we need a valid gtalk ID
    • Password-password for the above account
    • To-who to send e-mail to?
    • Subject-Email subject
    • Body-the actual email message

We have not considered any of the above properties of any validation, validation will be added in the next chapter. Now let's take a look at the Execute () method. The Execute () method uses the supplied parameters by using the Javax Mail library to send an e-mail message. If the message is sent, the action returns SUCCESS, otherwise it returns an error.

Create a home page:
Let's write the JSP file for the home page index.jsp, which will be used to collect information about the emails mentioned above:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding=" iso-8859-1 "%> <%@ taglib prefix=" s "uri="/struts-tags "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

To create a view:
We will use the JSP file success.jsp will be invoked in case the action returns success, but in the event of an error, we will have another view that the file is returned from the operation.

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
 pageencoding=" iso-8859-1 "%> <%@ taglib prefix="
S "uri="/struts-tags "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" 
"HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
< html>
 
 

The following will be in the case of an error, returning the view file error.jsp from the action.

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "
 pageencoding=" iso-8859-1 "%> <%@ taglib prefix="
S "uri="/struts-tags "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" 
"HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
< html>
 
 

Configuration file:
Now, let's put it all together. Use the Struts.xml configuration file as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
  "-//apache Software foundation//dtd struts Configuration 2.0//en"
  "http:// Struts.apache.org/dtds/struts-2.0.dtd ">

<struts>

  <constant name=" Struts.devmode "value=" true "/>
  <package name=" HelloWorld "extends=" Struts-default ">

   <action name=" Emailer "class=" 
     Com.yiibai.struts2.Emailer "
     method=" "Execute" >
     <result name= "Success" >/success.jsp</result >
     <result name= "error" >/error.jsp</result>
   </action>

  </package>

</struts>

The following are the contents of the Web.xml file:

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /2001/xmlschema-instance "xmlns=" Http://java.sun.com/xml/ns/javaee "xmlns:web=" Http://java.sun.com/xml/ns/javaee /web-app_2_5.xsd "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ Web-app_3_0.xsd "id=" webapp_id "version=" 3.0 "> <display-name>struts 2</display-name> <welcome-f ile-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <f Ilter-name>struts2</filter-name> <filter-class> Org.apache.struts2.dispatcher.FilterDispatcher & lt;/filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> < url-pattern>/*</url-pattern> </filter-mapping> </web-app> 

Now, right click on the project name and click Export > War file to create a war document. This war is then deployed under Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Enter the information you want and click the Send Email button. If all goes well, you should see the following pages:


If the SSH three framework is used together, here's another example, but the struts and spring frameworks also need mail.jar,activation.jar.

1 First configure the Bean in the Applicationcontext.xml file

<bean id= "MailSender" class= "Org.springframework.mail.javamail.JavaMailSenderImpl" >
    <property name= " Host "value=" host "/> <property name=" username "value=" username "/> <property name="
    password " value= "Password"/>
  </bean> <bean id= "sendmailaction" class= "Cn.com.action.SendMailAction"

Singleton= "false" >
   <property name= "MailSender" ><ref bean= "MailSender"/> </property>
</bean>

2 implementation of sending mail Java class code

protected Javamailsenderimpl MailSender;


public class Sendmailaction extends actionsupport{public
void Setmailsender (Javamailsenderimpl mailsender) {
  This.mailsender = MailSender;
}


public void SendMail () throws Exception {

1: Simple Mail

protected Javamailsenderimpl MailSender;


public class Sendmailaction extends actionsupport{public
void Setmailsender (Javamailsenderimpl mailsender) {
  this.mailsender = MailSender;
}


public void SendMail () throws Exception {

Sending 2:html messages

Create mail messages, send simple messages and HTML messages with the difference 
   mimemessage mailmessage = Senderimpl.createmimemessage (); 
   Mimemessagehelper messagehelper = new Mimemessagehelper (mailmessage); 
         
  Set recipient, sender 
   Messagehelper.setto ("sun111@163.com"); 
   Messagehelper.setfrom ("webadmin@163.com"); 
   Messagehelper.setsubject ("Test HTML mail!") "); 
  True to start the HTML-formatted message 
   messagehelper.settext (" 
 

3: Nested pictures in this class of test messages

Create mail messages, send simple messages and HTML messages with the difference 
   mimemessage mailmessage = Senderimpl.createmimemessage (); 
  Note that the boolean here equals the real time to nest the picture, and the value given when the build Mimemessagehelper is true means enabled,     
multipart mode 
   mimemessagehelper Messagehelper = new Mimemessagehelper (mailmessage,true); 
   
  Set recipient, sender 
   Messagehelper.setto ("sun111@163.com"); 
   Messagehelper.setfrom ("webadmin@163.com"); 
   Messagehelper.setsubject ("Nested pictures in the test message!!") "); 
  True to start the HTML-formatted message 
   messagehelper.settext (" 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.