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的post

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

用Session.getInstance替换Session.getDefaultInstance。

如果这不能解决问题,请阅读JavaMail FAQ,其中包含调试技巧。

请试试这个,

  public class SMTPDemo { public static void main(String args[]) throws IOException, UnknownHostException { String msgFile = "file.txt"; String from = "java2s@java2s.com"; String to = "yourEmail@yourServer.com"; String mailHost = "yourHost"; SMTP mail = new SMTP(mailHost); if (mail != null) { if (mail.send(new FileReader(msgFile), from, to)) { System.out.println("Mail sent."); } else { System.out.println("Connect to SMTP server failed!"); } } System.out.println("Done."); } static class SMTP { private final static int SMTP_PORT = 25; InetAddress mailHost; InetAddress localhost; BufferedReader in; PrintWriter out; public SMTP(String host) throws UnknownHostException { mailHost = InetAddress.getByName(host); localhost = InetAddress.getLocalHost(); System.out.println("mailhost = " + mailHost); System.out.println("localhost= " + localhost); System.out.println("SMTP constructor done\n"); } public boolean send(FileReader msgFileReader, String from, String to) throws IOException { Socket smtpPipe; InputStream inn; OutputStream outt; BufferedReader msg; msg = new BufferedReader(msgFileReader); smtpPipe = new Socket(mailHost, SMTP_PORT); if (smtpPipe == null) { return false; } inn = smtpPipe.getInputStream(); outt = smtpPipe.getOutputStream(); in = new BufferedReader(new InputStreamReader(inn)); out = new PrintWriter(new OutputStreamWriter(outt), true); if (inn == null || outt == null) { System.out.println("Failed to open streams to socket."); return false; } String initialID = in.readLine(); System.out.println(initialID); System.out.println("HELO " + localhost.getHostName()); out.println("HELO " + localhost.getHostName()); String welcome = in.readLine(); System.out.println(welcome); System.out.println("MAIL From:<" + from + ">"); out.println("MAIL From:<" + from + ">"); String senderOK = in.readLine(); System.out.println(senderOK); System.out.println("RCPT TO:<" + to + ">"); out.println("RCPT TO:<" + to + ">"); String recipientOK = in.readLine(); System.out.println(recipientOK); System.out.println("DATA"); out.println("DATA"); String line; while ((line = msg.readLine()) != null) { out.println(line); } System.out.println("."); out.println("."); String acceptedOK = in.readLine(); System.out.println(acceptedOK); System.out.println("QUIT"); out.println("QUIT"); return true; } } } 

有这个完全相同的问题。 您必须关闭catch块中的传输。 代码冻结的原因是因为除非您手动执行,否则smtp服务器连接永远不会在客户端关闭。

  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(); Transport.close() } 

但是确保javamail正确退出的最有效方法是将javamail逻辑捆绑到一个try块中并在finally块中关闭传输。 尝试这个。 [编辑]在被警告上述代码不起作用后,是正确编译的代码。

 import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; //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() throws MessagingException { Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", "localhost"); props.put("mail.smtp.auth", "false");// set to false for no username props.put("mail.debug", "false"); props.put("mail.smtp.port", "25"); Session session = Session.getDefaultInstance(props); InternetAddress fromAddress = null; InternetAddress toAddress = null; Transport transport = session.getTransport("smtp"); transport.connect(); try { Message simpleMessage = new MimeMessage(session); fromAddress = new InternetAddress(from); toAddress = new InternetAddress(to); simpleMessage.setFrom(fromAddress); simpleMessage.setRecipient(RecipientType.TO, toAddress); simpleMessage.setSubject(subject); simpleMessage.setText(text); transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients()); } catch (MessagingException e) { e.printStackTrace(); } finally { transport.close(); } } } 
  1. 禁用所有防病毒程序。
  2. 禁用防火墙。

然后尝试一下,如果你成功,进一步调查找到罪魁祸首。

在我的情况下,它是防病毒软件,我必须对SMTP上的出站邮件进行例外处理才能成功发送邮件。

当你声明Transport.send()它将无法使用它而不是transport.sendMessage(message, message.getAllRecipients()); 并声明一个javax.mail.Transport transport = session.getTransport("smtp"); 对象如代码所示。

  javax.mail.Transport transport = session.getTransport("smtp"); transport.sendMessage(message,message.getAllRecipients()); 

那么下面的代码就会出现这样谢谢你,希望这会完美无缺

 package org.java.vamsi; //import javax.activation.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Properties; //import java.io.*; //import javax.mail.internet.*; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.mail.Message.RecipientType; //import com.sun.corba.se.impl.protocol.giopmsgheaders.Message; //import java.io.*; //import java.util.*; //import javax.servlet.*; //import javax.servlet.http.*; //import javax.mail.*; //import javax.mail.internet.*; //import javax.activation.*; //import sun.rmi.transport.Transport; public class SendEmail extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Recipient's email ID needs to be mentioned. String to = "mysore.vamsikrishna@gmail.com"; // Sender's email ID needs to be mentioned String from = "mysore.vamsikrishna007@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ javax.mail.Transport transport = session.getTransport("smtp"); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(RecipientType.TO, new InternetAddress(to));//as we are importing the "javax.mail.Message.RecipientType" //we have to not set the type as this message.addRecipient(Message.RecipientType.TO, //new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message transport.sendMessage(message, message.getAllRecipients()); String title = "Send Email"; String res = "Sent message successfully...."; String docType = "\n"; out.println(docType + "\n" + "" + title + "\n" + "\n" + "

" + title + "

\n" + "

" + res + "

\n" + ""); }catch (MessagingException mex) { mex.printStackTrace(); } } }

我有完全相同的问题。 我花了好几个小时才找到问题的根源。 我使用了错误的依赖/依赖组合……

   javax.mail javax.mail-api 1.6.1   com.sun.mail javax.mail 1.5.3  

把它改成……

   javax.mail javax.mail-api 1.5.3   com.sun.mail javax.mail 1.5.3  

……解决了这个问题。