Session. In JavaMail The application of getdefaultinstance | 533 reports an error

Posted by toddmarx on Fri, 18 Feb 2022 11:25:59 +0100

Error content: 553 envelope sender mismatch with login user or Not connected
It means that the sender does not match the login user, that is, the mailName and fromAddress do not match, but it is the same in the actual project.

The following is the content collected online that can solve the problem.

Recently, I found a special phenomenon in the process of modifying the bug. In the email sending function, there was a problem that the account number did not match when I sent an email after modifying the account number and password
After carefully checking the relevant codes, it is found that the original developer actually has quite simple functions. He didn't even check the simplest mail format, and only gave a painless prompt after executing the mail sending program. He didn't even know whether the sending was successful or failed Nevertheless, now it's my turn to take charge, and I have to change it

The Jsp side is quite simple:

String[] receiver = {request.getParameter("receiver")};

String mail_subject = "Itmanager Mail Test.";
String mail_content = "Itmanager Mail Test";
Session mailSession = MailUtil.getSession(RptTaskMailConfig.SMTPServer,true,RptTaskMailConfig.Sender,RptTaskMailConfig.EmailPwd);
    catch (Exception e)


 * Gets the Session instance of the specified SMTP server
 * @param host
 * @param isAuth
 * @param user
 * @param password
 * @return
public static Session getSession(String host, boolean isAuth, String user, String password) {
    Properties props = new Properties();
    props.put("", host);
    props.put("mail.smtp.auth", String.valueOf(isAuth));

    Session session;
    if (user != null && user.length() > 0) {
        Authentic authentic = new Authentic(user, password);
        session = Session.getDefaultInstance(props, authentic);
    } else {
        session = Session.getDefaultInstance(props, null);

    return session;

 * Send message in text format
 * @param session
 * @param from
 * @param to
 * @param cc
 * @param subject
 * @param content
 * @param attachfile
public static void sendTextMessage(Session session, String from, String[] to, String[] cc, String subject,
        String content, Vector<File> attachfile) throws MessagingException {
    sendMessage(session, from, to, cc, subject, content, MIMETYPE_Default_TEXT, attachfile);

 * Send mail
 * @param session
 * @param from Sender
 * @param to addressee
 * @param cc CC
 * @param subject theme
 * @param content content
 * @param mimeType
 * @param attachfile Attachment file name list
public static void sendMessage(Session session, String from, String[] to, String[] cc, String subject,
        String content, String mimeType, Vector<File> attachfile) throws MessagingException {
    // Compare sender
    if (!isValidMailAddress(from)) {

    try {
        Message message = new MimeMessage(session);
        InternetAddress sendFrom = new InternetAddress(from);
        message.setHeader("X-Mailer", "ITManager Mailer");
        message.setHeader("From", "<" + from + ">");

        // Set recipient
        InternetAddress[] sendTo = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
        message.setRecipients(Message.RecipientType.TO, sendTo);

        // Set CC
        if (cc != null) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress(cc[i]);
            message.setRecipients(Message.RecipientType.CC, copyTo);

        // set up themes
        message.setSubject((subject == null || subject.length() == 0) ? "No subject" : MimeUtility

        // Set body
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent(content, mimeType);

        // Add attachment
        if (attachfile != null) {
            Enumeration<File> efile = attachfile.elements();
            while (efile.hasMoreElements()) {
                File ele = efile.nextElement();
                mbp = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(ele);
                mbp.setDataHandler(new DataHandler(fds));
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                mbp.setFileName("=?GBK?B?" + enc.encode(fds.getName().getBytes()) + "?=");
                // mbp.attachFile(ele);

        // Set sending date
        message.setSentDate(new Date());

        long start = System.currentTimeMillis();
        System.out.println("Start time:" + start);
        long end = System.currentTimeMillis();
        System.out.println("End time:" + end);
        System.out.println("Send time:" + (end - start) + "ms");
    } catch (IOException ioe) {
    } catch (NoSuchProviderException nspe) {
    } catch (MessagingException me) {
        throw me;

The whole logic of the program is relatively clear. Adjust javax Mail package, directly using days of transport Send (message) function of sending mail However, when you enter the system for the first time, you can send mail normally, but if you change the email user name, password and other data and then send it, it will report an exception According to the preliminary judgment, there was an error in the incoming data of the jsp page. Enter the debug state for debugging and find mailutil The value in getsession (rpttaskmailconfig. Smtpserver, true, rpttaskmailconfig. Sender, rpttaskmailconfig. Emailpwd) is the newly changed value after saving I fell into confusion. Since it was a new value, why did I report that the account and password did not match Continue debugging. It is estimated that the problem is the session. It should be that the first session has not been cleared, but after checking the information on the Internet, it is not said that the session needs to be specially cleared after java mail is sent, and mailutil. Is called every time in the program Getsession will generate different sessions, which does not seem to exist Finally, it is found that when the session is established, the session getDefaultInstance(props, authentic); Quite suspicious Checked:

What is getDefaultInstance?

As can be seen from the processing flow, the first step is to find out whether there are properties in the cache
If so, load the default properties
If it does not exist, load the user-defined properties,
Therefore, when an application creates properties independently for each user, it should still call getInstance,
Unless you want to have a default property for users to use

The problem is found, because it will first look for properties in memory and system files. Therefore, no matter how many times I change the data on the page, the generation of session in the background is the same as that when the system is started.

So in mailutil sendTextMessage(mailSession,RptTaskMailConfig.Sender,
receiver,null,mail_subject,mail_content,“GB2312”,null); The sender in the session is inconsistent with the sender passed in, so an error occurs. Modify the session getDefaultInstance(props, authentic); Is session getInstance(props, authentic); After, you can correctly send the email after modifying the account, password and other information OK

Finally, session The difference between getdefaultinstance and getinstance:

If you want to use two accounts to send javamail at the same time, for example Send 1# mail using To send 2# mail, you need to create two Java mail. Session object. But if you still use session If getDefaultInstance creates a session object, you will find that the second Username: The created session is always the same as the first one. Why? Because getDefaultInstance is a real singleton mode, and the username and password attributes are final and cannot be changed. So you'll find that both email s were sent by Sent it. So you need to use javax mail. Session. GetInstance () method to create a session object.

Topics: javamail