Javamail从2个smtp服务器发送消息

时间:2017-02-27 18:33:36

标签: javamail

我遇到了问题,需要一些帮助

在我的程序中我需要发送邮件和smtp服务器取决于一个var, 如果var为1则必须从gmail地址发送邮件 或者如果var为2,邮件将从不同的smtp服务器发送

我从两个帐户使用TLS,一切正常(如果只从1台服务器发送)...但是当我尝试从两台服务器发送时(因为我的var变化取决于1到2,或2到1次多次在执行期间)我总是收到错误

这是我的代码:

public static void correo(String empresa, String[] dest, String archivo, String nom_arch){
    String cuenta = "", asunto = "", pw = "", pto = "", server = "";
    try
    {
        Properties props = new Properties();

        if("1".equals(empresa)){
            cuenta = "example@gmail.com";
            asunto = "xxxxxxx";
            pw = "password";
            pto = "587";
            server = "smtp.gmail.com";
        }
        else if ("2".equals(empresa)) {
            cuenta = "example@server.com";
            asunto = "yyyyyyy";
            pw = "password";
            pto = "25";
            server = "smtpout.secureserver.net";
        }

        props.setProperty("mail.smtp.host", server);
        props.setProperty("mail.smtp.port", pto);
        props.setProperty("mail.smtp.user", cuenta);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props,null);

        BodyPart texto = new MimeBodyPart();
        texto.setText("Some Text");

        BodyPart adjuntoPDF = new MimeBodyPart();
        adjuntoPDF.setDataHandler(new DataHandler(new FileDataSource(archivo+".pdf")));
        adjuntoPDF.setFileName(nom_arch+".pdf");

        MimeMultipart multiparte = new MimeMultipart();
        multiparte.addBodyPart(texto);
        multiparte.addBodyPart(adjuntoPDF);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(cuenta));

        InternetAddress[] direcciones = new InternetAddress[dest.length];
        for(int i=0; i<dest.length; i++){
            direcciones[i] = new InternetAddress(dest[i]);
        }
        message.addRecipients(Message.RecipientType.TO,direcciones);
        message.setSubject(asunto);
        message.setContent(multiparte);

        Transport t = session.getTransport("smtp");
        t.connect(cuenta, pw);
        t.sendMessage(message, message.getAllRecipients());

        t.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

请参阅common JavaMail mistakes的此JavaMail FAQ列表。将Session.getDefaultInstance更改为Session.getInstance。