Java Mail和Database连接存在冲突

时间:2014-12-08 11:17:26

标签: java email jdbc

这是我的整个java代码。如果我评论该行: objCon = DriverManager.getConnection(props.getString("url"));邮件正在正确发送。否则,它会抛出错误 - Could not connect to SMTP host: mail.companyname.com, port: 25;

public class PullRec {

private static final Logger LOG_TRACE = Logger.getLogger("debugLogger");

public static void main(String[] args) throws Exception {       
    Connection objCon = null;  
    PropertyResourceBundle props;
    props = (PropertyResourceBundle) ResourceBundle.getBundle("com.cts.properties.config");
    try {  
        Class.forName(props.getString("dbdriver"));
        // If I comment the below line, the sendmail function works perfectly..!!  
        objCon = DriverManager.getConnection(props.getString("url"));
    }
    catch(Exception e) {
        LOG_TRACE.info("DBConnection.java FILE ERROR: Disconnected due to "+e);     
    }
    sendmail("Test");

}

public static void sendmail(String strBody) {

      String to = "sarath@companyname.com";

      String from = "sarath@companyname.com";

      String host = "mail.companyname.com";

      Properties properties = System.getProperties();

      properties.setProperty("mail.smtp.host", host);
      properties.setProperty("java.net.preferIPv4Stack","true");

      Session session = Session.getDefaultInstance(properties);

      try{
         MimeMessage message = new MimeMessage(session);

         message.setFrom(new InternetAddress(from));

         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         message.setSubject("CTS Monitor");

         message.setContent(strBody,"text/html" );  

         Transport.send(message);

         System.out.println("Sent message successfully....");
      }
      catch (MessagingException e) {
         e.printStackTrace();
      } 
}
}

1 个答案:

答案 0 :(得分:1)

您的mail方法明确将SMTP服务器主机名设置为"<hostname>"。这永远不会奏效。您需要将其替换为您尝试使用的SMTP服务器的 real DNS主机名。

(您的fromto地址也不太可能有效......)


如果您已经这样做但仍然无法正常工作,请检查您的(实际)主机名和端口是否正确,以及该主机/端口上的SMTP服务器是否处于活动状态。


我注意到您已对用于配置邮件服务器的mail(String)的通话进行了注释,但我不确定您的Mail对象是什么,或sendmail是什么方法实际上是在做。

(注意:这不是你的所有Java代码,因为如果是,它就不会编译!)