Java Implementation mailbox retrieve password Simple Mail

Source: Internet
Author: User
Tags server website email account server port ssl connection

First the sender's POP/SMTP service to hit the developer's password for the service authorization code

JS method

Retrieve password
function Send () {
var Lostemail = $ ("#lostemail"). Val ();
if (! ( /^\w[-\w.+]*@ ([a-za-z0-9][-a-za-z0-9]+\.) +[a-za-z]{2,14}$/.test (lostemail)) {//Mailbox format verification
LAYER.MSG ("Email format is incorrect, please re-enter");
$.ajax ({
URL: ' ${cjq}/email/sendemail ',
Type: ' POST ',
Data: {
Error:function () {
LAYER.MSG (' Network error! ');
Success:function (data) {
LAYER.MSG (data);


--------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------

Sender class

Package cn.mybatis.Api;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;

Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.RequestParam;
Import Org.springframework.web.bind.annotation.ResponseBody;

Import Cn.mybatis.Model.Response;
Import Cn.mybatis.Model.User;
Import Cn.mybatis.Service.UserService;
Import Cn.mybatis.Util.EmailUtils;

Import Java.util.Date;
Import java.util.Properties;

@RequestMapping ("/email")
public class sendemail{
Private UserService UserService;
Sender's mailbox and password (replaced by their mailbox and password)
PS: Some mailbox servers in order to increase the security of the mailbox itself password, to the SMTP client set up a separate password (some mailboxes called "Authorization Code"),
For a mailbox with a separate password, the password for the mailbox must be used for this individual password (authorization code).
public static String myemailaccount = Emailutils.myemailaccount;
public static String Myemailpassword = Emailutils.myemailpassword;

The SMTP server address of the sender's mailbox must be accurate, different mail server addresses are different, general (only general, not absolute) format:
NetEase 163 the SMTP server address of the mailbox is:
public static String myemailsmtphost = Emailutils.myemailsmtphost;

//Recipient mailbox (default mailbox)
//public static String receivemailaccount = "[email protected]";

@RequestMapping (value = "/sendemail", method =
@ responsebody         //is important
public String sendEmail (@RequestParam (value = "Lostemail ", required = False) String lostemail) {
User User =userservice.selectuserbyemail (lostemail);
if (user==null) {
Return "does not have this mailbox, please re-enter or contact the administrator!";

///1. Create a parameter configuration to connect the parameter configuration of the mail server
Properties props = new properties ();//Parameter Configuration
Props.setproperty ("Mail. Transport.protocol "," SMTP "); protocol used (JavaMail specification required)
Props.setproperty ("", emailutils.myemailsmtphost);//SMTP server address for sender's mailbox
Props.setproperty ("Mail.smtp.auth", "true"); Need to request authentication

//PS: Some mailbox servers require SSL security authentication for SMTP connections (to improve security, the mailbox supports SSL connections, you can turn it on yourself),
//If you cannot connect to the mail server, carefully view the log that is printed on the console, if there is a similar "connection failed, Require SSL secure connection "such as error,
//Open the comment code in the following//* ... */To turn on SSL secure connection.

//SMTP server port (non-SSL port generally defaults to 25, can not be added, if the SSL connection is turned on,
//need to change the port of the SMTP server corresponding to the mailbox, specifically to see the corresponding mailbox service Help,
//Q Q The SMTP (SLL) port of the mailbox is 465 or 587, the other mailboxes go to see for themselves)
Final String smtpport = "465";
Props.setproperty ("Mail.smtp.port", Smtpport);
Props.setproperty ("Mail.smtp.socketFactory.class", "");
Props.setproperty ("Mail.smtp.socketFactory.fallback", "false");
Props.setproperty ("Mail.smtp.socketFactory.port", Smtpport);
Props.setproperty ("Mail.smtp.ssl.enable", "true");

//2. Create a Session object based on configuration for interacting with the mail server
Session session = Session.getdefaultinstance (props);
Session.setdebug (true); Set to debug mode, you can view detailed send log

3. Create a message
MimeMessage message;
try {
Message = Createmimemessage (Session, Emailutils.myemailaccount, Lostemail,user);

4. Get message transfer objects based on Session
Transport Transport = Session.gettransport ();

5. Use your email account and password to connect to the mail server, where the authenticated mailbox must match the sender's mailbox in the message, otherwise the error
PS_01: The key to success or failure in this sentence, if the connection server fails, it will output the log of the corresponding failure reason in the console.
Carefully review the reason for the failure, and some mailbox servers will return an error code or see a link to the error type, depending on the given error
Type to the corresponding mail server on the help site to see the specific failure reason.
PS_02: The reason for the connection failure is usually the following, carefully examining the code:
(1) The mailbox does not have SMTP service turned on;
(2) e-mail password error, for example, some mailboxes open a separate password;
(3) The mailbox server requires that SSL secure connection be used;
(4) The request is too frequent or other reasons, the mail server refused service;
(5) If the above points are OK, go to the mail server website to find help.
PS_03: Look at log carefully, read the log carefully, read the log, the cause of the error is described in log.
Transport.connect ("", Emailutils.myemailaccount, Emailutils.myemailpassword);

6. Send a message to all of the receiving addresses, message.getallrecipients () gets all the recipients that were added when the message object was created, Cc, BCC.
Transport.sendmessage (Message, message.getallrecipients ());
7. Close connection
Transport.close ();
} catch (Exception e) {
E.printstacktrace ();
Return "Mail failed to send, may be the wrong email address, please contact the administrator!";
Return "Mail sent successfully, please pay attention to check!";

* Create a simple message that contains only text
* Sessions @param session and server interaction
* @param sendMail Sender Mailbox
* @param receivemail Recipient mailbox
* @return
* @throws Exception
Public MimeMessage Createmimemessage (Session session, String SendMail, String Receivemail,user User) throws Exception {
1. Create a message
MimeMessage message = new MimeMessage (session);

2. From: Sender (nickname is suspected of advertising, to avoid being mistaken by the mail server is spamming and return failure, please modify the nickname)
Message.setfrom (New InternetAddress (SendMail, "strong net", "UTF-8"));

3. To: Recipient (can add multiple recipients, CC, BCC)
Message.setrecipient (MimeMessage.RecipientType.TO, New InternetAddress (Receivemail, User.getusername () + "user", " UTF-8 "));

4. Subject: The subject of the message (the title is suspected of advertising, to avoid being mistaken by the mail server is spamming and return failure, please modify the title)
Message.setsubject ("Retrieve Password", "UTF-8");

5. Content: Message body (HTML tags can be used) (the content is suspected of advertising, to avoid being mistaken by the mail server for spamming and return failure, please modify the content sent)
Message.setcontent (User.getusername () + "User Hello, your login password for" +user.getpassword () + ", please note to save the password, to prevent leakage, thank you for your strong support, I wish you a happy life ... "," Text/html;charset=utf-8 ");

6. Set the Send time
Message.setsentdate (New Date ());

7. Save Settings
Message.savechanges ();

return message;

Java Implementation mailbox retrieve password Simple 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: 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.