java – Transport.send(消息)在以下代码中不起作用.. netbeans卡在运行部分.它不会继续下去……它永远挂在那里

我曾尝试编写使用Java发送电子邮件的代码.但是这段代码不起作用.当代码执行时,它会卡在transport.send(消息)上.它永远停留在那里.此外,我不确定其余代码是否正确.

  //first from,to,subject,& text values are set
    public class SendMail {
    private String from;
    private String to;
    private String subject;
    private String text;


    public SendMail(String from,String to,String subject,String text){
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }

    //send method is called in the end 
    public void send(){

        Properties props = new Properties();
        props.put("mail.smtp.host","smtp.gmail.com");
        props.put("mail.smtp.port","465");

        Session mailSession = Session.getDefaultInstance(props);
        Message simpleMessage = new MimeMessage(mailSession);

        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;
        try {
            fromAddress = new InternetAddress(from);
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(RecipientType.TO,toAddress);
            simpleMessage.setSubject(subject);
                    simpleMessage.setText(text);
            Transport.send(simpleMessage);  // this is where code hangs     
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
}
最佳答案
我遇到了完全相同的问题,其他人报告了间歇性故障.原因是带有SMTP的Transport.send有两个无限超时,这可能导致您的进程挂起!

来自SUN文档:

mail.smtp.connectiontimeout int套接字连接超时值,以毫秒为单位.默认为无限超时.

mail.smtp.timeout int套接字I / O超时值,以毫秒为单位.默认为无限超时.

要不永远“挂起”,您可以明确地设置它们:

来自SUN:属性始终设置为字符串; Type列描述了如何解释字符串.例如,使用

    props.put("mail.smtp.port","888");

请注意,如果您使用“smtps”协议访问SMTP over SSL,则所有属性都将命名为“mail.smtps.*”.

因此,如果设置两个超时,则应该得到一个“MessagingException”,您可以使用try / catch处理它,而不是让进程挂起.

假设您正在使用smtp,请添加以下内容,其中t1和t2是您的超时时间:

    props.put("mail.smtp.connectiontimeout","t1");
    props.put("mail.smtp.timeout","t2");

当然,这不会解决超时的根本原因,但它可以让您优雅地处理问题.

感谢Siegfried Goeschl在Apache Commons的帖子

PS:我遇到的问题的根本原因似乎与我在旅行时使用的网络连接有关.显然,连接导致SMTP超时,我没有与任何其他连接.

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...