Javamail:第二次连接失败:连接到不同的主机和端口

Javamail: second time connection failure: connect to different host and port

我正在 Java EE 项目中使用 Javamail 发送邮件,我正在本地主机上进行测试。我第一次使用下面的代码可以发送邮件,但第二次我不能,并且控制台显示它尝试连接到本地主机,这在第一次没有发生。

第一次控制台消息:

DEBUG: JavaMail version 1.5.1
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.1and1.es", port 465, isSSL false
220 kundenserver.de (mreue104) Nemesis ESMTP Service ready
DEBUG SMTP: connected to host "smtp.1and1.es", port: 465

....(more host/connection/email content details, but the connection is established)

第二次控制台消息:

DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "localhost", port 25, isSSL false

它停止并且什么也不做。

properties(smtp 段):

mail.smtp.protocol=smtp
mail.smtp.useTSL=true
mail.smtp.auth=true
#mail.smtp.host=smtp.redfinanciera.es
mail.smtp.host=smtp.1and1.es
mail.smtp.port=465

邮件发件人代码:

public CCorreo mandarCorreo(CCorreoForm form) {

        InputStream input = null;
        Properties prop = null;
        CCorreo correo = null;
        try {
            //leer prop y mandar mensajes
            input = MailSmtpSender.class.getResourceAsStream("/config/properties/mail.properties");
            prop = new Properties();
            prop.load(input);
            final String smtpUser = prop.getProperty("mail.smtp.user");
            final String smtpPassword = prop.getProperty("mail.smtp.pass");

            //prop setting de smtp.
            prop.setProperty("mail.smtp.connectiontimeout", "5000");
            prop.setProperty("mail.smtp.timeout", "5000");
            prop.put("mail.smtp.starttls.enable", "true");
            prop.put("mail.debug", "true");
            //socket factory port: default if null
            prop.put("mail.smtp.socketFactory.port", "465");
//          prop.put("mail.smtp.socketFactory.port", "*");
            prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.put("mail.smtp.socketFactory.fallback", "false");

            //crear una sesion. con autentificacion SSL
            Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {  
                   return new PasswordAuthentication(smtpUser, smtpPassword);  
               }  
            });
            //construir message
            MimeMessage message = new MimeMessage(session);
            message.setFrom(prop.getProperty("mail.smtp.from"));
            if (!StringUtils.isEmpty(form.getCuerpo())){
                message.setText(form.getCuerpo(), "UTF8");
            } else {
                message.setText("");
            }
            message.setSubject(form.getAsunto(), "UTF8");

                //construir receptor. sacar de form.
            String[] addressesString = {form.getReceptor()};
            InternetAddress addresses[] = new InternetAddress[addressesString.length];
            for (int i = 0; i < addressesString.length; i++){
                 addresses[i] = new InternetAddress(addressesString[i].trim().toLowerCase());
            }
            message.setRecipients(Message.RecipientType.TO, addresses);


                //formar el correo, rellenar todas las partes de el.
            Multipart mp = new MimeMultipart();
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setContent(form.getCuerpo(), "text/html;charset=utf-8");
            mp.addBodyPart(mbp);
            message.setContent(mp);
            message.setSentDate(new Date());

            //establecer un Transport y mandar el mensaje
            Transport.send(message);


        } catch (Exception e) {
            throw new RuntimeException("Se ha producido un error al mandar el correo. Mensaje: " + e.getMessage());
        } finally {
            prop.clear();
            try {
                input.close();
            } catch (IOException e) {
                System.out.println("Se ha producido un error al mandar el correo. Mensaje: " + e.getMessage());

            }
        }
        return correo;

    }

所以问题来了:为什么它第一次使用端口 465 连接到 smtp 服务器,但在第二次尝试连接到本地主机并使用端口 25??? 它是太奇怪了。

编辑:

我在AngularJS中打开一个lightbox/modal来发送邮件。发送电子邮件后,灯箱将关闭并再次显示主页。我发现如果我不刷新主页,我不能再次发送电子邮件,但如果我刷新,它工作正常。我想弄清楚为什么会这样,也希望能找到关于这个的答案。

您的代码包含许多 common JavaMail mistakes JavaMail 常见问题解答中描述的内容。

特别是,您的问题很可能是由您使用 Session.getDefaultInstance instead of Session.getInstance 引起的,但您需要解决上述 link 中的所有问题。