Javaweb Small Knowledge Learning--java Mail

Source: Internet
Author: User

This article mainly uses the Java mail and Spring Mail two ways to send the message tutorial, compared verbose, because in addition to send mail also wrote other tool class, but very detailed.

1. Send mail using Java Mail

First, the relevant account password information is saved to a properties, read injected into the Mailutil tool class, and then the controller calls the Mailutil inside the Send mail method, because the email is a time-consuming process, so put in a thread inside run.

1.1. Read the configuration file

Create a config.properties file, write the following configuration ( Most mailboxes now open SMTP to give you an authorization code, using authorization code authentication, and the port may be 465, such as QQ, this to check the mailbox settings yourself )

#mail配置mail.host = smtp.163.commail.protocol = smtpmail.port25mail.user = 邮箱账号mail.pwd = 授权码

Write a Propertiesutil.java tool class to read these configurations

 PackageCn.edu.aust.util;Importjava.io.*;ImportJava.util.Properties;/** * Tool class for reading properties files */ Public  class propertiesutil {    Private StaticProperties Properties;Private StaticString URL;Static{URL = system.getproperty ("Web.root") +"Web-inf"+file.separator+"Classes"+file.separator+"Config.properties"; Properties =NewProperties ();Try{InputStream in =NewBufferedinputstream (NewFileInputStream (URL));        Properties.load (in); }Catch(IOException e)        {E.printstacktrace (); }    }/** * Read properties * @param key * @return * /     Public StaticStringGetProperty(String key) {returnProperties.getproperty (key); }/** * Set properties * @param key * @param value */     Public Static void SetProperty(String key,string value)throwsIOException {OutputStream out =NewFileOutputStream (URL);        Properties.setproperty (Key,value); Properties.store (out," " Comments "Update key:"+ key); }}
1.2mailutil.java Tool Class

First maven joins Mail support:

    <!-- mail支持 -->    <dependency>      <groupId>javax.mail</groupId>      <artifactId>mail</artifactId>      <version>1.4.7</version>    </dependency>

Overall steps to send a message:

    • Construction session
    • – Constructs a authenticator class that holds the user name password
    • – Read the configuration and put it in a properties instance
    • Construct mail
    • Send mail
      It's only written here. Send Plain text files
/** * Tool class for sending mail * / Public  class mailutil {    Private StaticString HOST;Private StaticString PROTOCOL;Private StaticString PORT;Private StaticString USER;//Sender Account    Private StaticString PWD;//Sender Password    Static{HOST = Propertiesutil.getproperty ("Mail.host"); PROTOCOL = Propertiesutil.getproperty ("Mail.protocol"); PORT = Propertiesutil.getproperty ("Mail.port"); USER = Propertiesutil.getproperty ("Mail.user"); PWD = Propertiesutil.getproperty ("Mail.pwd"); }/** * 1. Get session * @return  */     Public StaticSessiongetsession(){//1.1 constructs a authenticator class that holds the user name passwordAuthenticator Authenticator =NewAuthenticator () {@Override            protectedPasswordauthenticationgetpasswordauthentication() {return NewPasswordauthentication (USER,PWD);        }        }; Properties props =NewProperties (); Props.put ("Mail.smtp.host", HOST); Props.put ("Mail.store.protocol", PROTOCOL); Props.put ("Mail.smtp.port", PORT); Props.put ("Mail.smtp.auth",true);returnSession.getdefaultinstance (Props,authenticator); }/** * 2. Send messages without attachments * @param toemail * @param content * *     Public Static void Send(String toemail,string content)throwsMessagingexception {Session session = GetSession (); Logger.debug ("Ready to send a message to"+toemail);//2.1 Construct MessageMessage msg =NewMimeMessage (session); Msg.setfrom (NewInternetAddress (USER)); Msg.setrecipient (Message.RecipientType.TO,NewInternetAddress (Toemail)); Msg.setsubject ("Account activation Email"); Msg.setsentdate (NewDate ()); Msg.setcontent (Content,"Text/html;charset=utf-8");//2.2 sends a message because it is sent slowly and is placed in a threadThread T =NewThread (()->{Try{transport.send (msg); Logger.info ("Send message successfully"+toemail); }Catch(Messagingexception e)            {E.printstacktrace ();        }        });    T.start (); }Private StaticLogger Logger = Logger.getlogger (Mailutil.class);}

This method of sending a simple text message is complete.

2.Spring Mail

First include the configuration of the mail server in the spring configuration file

<!--load the mail profile --    <context:property-placeholder location ="Classpath:config.properties"/> <!--Mail Service start -up    <bean id= "mailsender" class=" Org.springframework.mail.javamail.JavaMailSenderImpl ">        < property name="Host" value="${mail.host}" />         < property name="Port" value="${mail.port}"/>        < property name="username" value="${mail.user}" />        < property name="password" value="${mail.pwd}" / >        < property name="defaultencoding" value="UTF-8"/>        < property name="Javamailproperties">            <props>                <prop key="Mail.smtp.auth">True</prop>                <prop key="Mail.smtp.timeout">25000</prop>            </props>        </Property >    </Bean>    <!--is used to asynchronously execute a thread pool for sending messages--    <bean id= "mailtaskexecutor" class=" Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor ">        < property name="Corepoolsize" value="Ten"/>        < property name="Maxpoolsize" value="/> "    </Bean>    < end of!--mail Service --

The specific delivery is very simple, the overall steps and before the same

@Controller Public  class testcontroller {    @Resource(name ="MailSender")PrivateJavamailsenderimpl Sender;@Resource(name ="Mailtaskexecutor")PrivateTaskexecutor Taskexecutor;/** * Send normal text operation * @return  */    @RequestMapping(Value ="/test", method = Requestmethod.get) PublicStringtotest()throwsmessagingexception {Simplemailmessage message =NewSimplemailmessage ();        Message.setfrom (Sender.getusername ()); Message.setto ("[email protected]"); Message.setsubject ("Activate Mail"); Message.settext ("Hello World");        Taskexecutor.execute (()->{sender.send (message); });return "Test"; }}

If you want to send a message with an attachment, you can use MimeMessage to wrap it

 PublicStaticvoidSendString  to,StringSubjectStringTextStringFilename,file File) throws messagigexception{//Use JavaMail's mimemessage to pay for more complex message formats and contentMimeMessage msg=Sender.Createmimemessage ();//Create Mimemessagehelper object, handle MimeMessage auxiliary classMimemessagehelper Helper= NewMimemessagehelper (MSG,true);//Use auxiliary class MimeMessage to set parametersHelper.Setfrom (Sender.GetUserName ()); Helper.Setto ( to); Helper.Setsubject (subject); Helper.SetText (Text,true);//Add Attachment    if(File!=NULL) Helper.AddAttachment (fileName, file);//Send mailSender.Send (msg);}
3. Verify activation

Look for a bit on the net, feel the following idea is the best

1. Database plus three fields, state: (0: Inactive, 1: Activation successful), Acticode: (release Activation Code), Token_exptime (expiration time, used to verify whether the activation message expired)

2. The user fills in the information, clicks the registration, inserts the data to be successful, the State field defaults is 0, simultaneously generates a acticode (with passes over the mailbox, the password, and the current time encryption form) also deposits the database

3. Send mail ... Prompt user to log on to mailbox activation ... There are two parameters (1, user id,2: Activation code) in the Url,url with an Activation Success page in the message.

4. User Login to the mailbox click on the link, to deal with the activation of the Business logic page or servlet, get the URL of two parameters, the two parameters to query the data in the database, if there is, take the current time and before the expiration time of the database to compare, see whether expired, expired, Delete the record in the database, and go to the failure page, not expired, check the link passed the Activation Code and database field activation code is consistent, inconsistent, delete the database in the record, and jump to the activation failure interface, consistent, the field State is 1, the activation succeeds, go to the Activation Success page ...

4. Forgot password function

From: http://www.jianshu.com/p/bc61e9192658
First step: Show the Forgotten Password page

A simple form page, enter a user name and a verification code that refreshes 60 seconds.
You need to verify that the user name exists and that the mailbox is filled in.
60 seconds of refreshed CAPTCHA prevents malicious password reset.
There are many verification codes implemented in 60 seconds, and the time information can be present in the session or cookie or Ehcache.

Step two: Send the message and cache the password reset token.

Generates a valid token within 5 minutes, and the token and user ID mappings are saved in Ehcache.
Use the token values to make a reset mail link.
Remove the email address from the database and send the message.

Step three: Reset your password

The user clicks the link to enter the Reset password screen.
Verify the token value, and get the user ID to navigate to the specific user.
The user modifies the password.

Javaweb Small Knowledge Learning--java Mail

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.