Java 传输。发送(消息)在以下代码中不起作用。。netbeans在运行部分卡住了。它没有';4.别再往前走了。。它永远挂在那里

Java 传输。发送(消息)在以下代码中不起作用。。netbeans在运行部分卡住了。它没有';4.别再往前走了。。它永远挂在那里,java,api,jakarta-mail,netbeans-6.9,Java,Api,Jakarta Mail,Netbeans 6.9,我试着用Java编写一个发送电子邮件的代码。但是这个代码不起作用。当代码被执行时,它会在transport.send(message)处卡住。它永远卡在那里。另外,我不确定代码的其余部分是否正确 //first from, to, subject, & text values are set public class SendMail { private String from; private String to; private String su

我试着用Java编写一个发送电子邮件的代码。但是这个代码不起作用。当代码被执行时,它会在transport.send(message)处卡住。它永远卡在那里。另外,我不确定代码的其余部分是否正确

  //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();
        }       
    }
}
请试试这个

    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;
    }
  }
}
公共类SMTPDemo{
公共静态void main(字符串args[])引发IOException,
未知后异常{
字符串msgFile=“file.txt”;
字符串from=”java2s@java2s.com";
字符串to=”yourEmail@yourServer.com";
字符串mailHost=“yourHost”;
SMTP邮件=新SMTP(邮件主机);
如果(邮件!=null){
if(mail.send(新文件读取器(msgFile)、from、to)){
System.out.println(“邮件已发送”);
}否则{
System.out.println(“连接到SMTP服务器失败!”);
}
}
System.out.println(“完成”);
}
静态类SMTP{
专用最终静态int SMTP_端口=25;
邮件主机地址;
本地主机地址;
缓冲读取器;
打印输出;
公共SMTP(字符串主机)引发UnknownHostException{
mailHost=InetAddress.getByName(主机);
localhost=InetAddress.getLocalHost();
System.out.println(“mailhost=“+mailhost”);
System.out.println(“localhost=“+localhost”);
System.out.println(“SMTP构造函数完成\n”);
}
公共布尔发送(FileReader msgFileReader、字符串从、字符串到)
抛出IOException{
承插短管;
InputStream酒店;
输出流输出;
缓冲阅读味精;
msg=新的BufferedReader(msgFileReader);
smtpPipe=新套接字(邮件主机、SMTP_端口);
如果(smtpPipe==null){
返回false;
}
inn=smtpPipe.getInputStream();
outt=smtpPipe.getOutputStream();
in=新的BufferedReader(新的InputStreamReader(inn));
out=新的PrintWriter(新的OutputStreamWriter(outt)),true;
如果(inn==null | | outt==null){
System.out.println(“未能将流打开到套接字”);
返回false;
}
字符串initialID=in.readLine();
System.out.println(initialID);
System.out.println(“HELO”+localhost.getHostName());
out.println(“HELO”+localhost.getHostName());
字符串welcome=in.readLine();
System.out.println(欢迎);
System.out.println(“邮件发件人:”);
out.println(“邮件发件人:”);
字符串senderOK=in.readLine();
系统输出打印LN(senderOK);
System.out.println(“RCPT TO:”);
out.println(“RCPT TO:”);
字符串recipientOK=in.readLine();
System.out.println(recipientOK);
系统输出打印项次(“数据”);
out.println(“数据”);
弦线;
而((line=msg.readLine())!=null){
out.println(行);
}
系统输出打印项次(“.”);
out.println(“.”);
字符串acceptedOK=in.readLine();
System.out.println(acceptedOK);
System.out.println(“退出”);
out.println(“退出”);
返回true;
}
}
}

用Session.getInstance替换Session.getDefaultInstance


如果这不能解决问题,请阅读JavaMail常见问题解答,其中有调试提示。

我遇到了完全相同的问题,其他人报告了间歇性故障。原因是Transport.send with SMTP有两个无限超时,这可能会导致进程挂起

来自SUN文档:

mail.smtp.connectiontimeout int套接字连接超时值(毫秒)默认值为无限超时。

mail.smtp.timeout int套接字I/O超时值(毫秒)默认值为无限超时。

若要永远不“挂起”,可以显式设置:

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

    props.put("mail.smtp.port", "888");
请注意,如果您使用“smtps”协议通过SSL访问SMTP,则所有属性都将命名为“mail.smtps.*”

因此,如果您设置了两个超时,您应该得到一个“MessaginException”,您可以通过try/catch处理它,而不是让进程挂起

假设您正在使用smtp,请添加以下内容,其中t1和t2是您的超时值,单位为毫秒:

    props.put("mail.smtp.connectiontimeout", "t1");
    props.put("mail.smtp.timeout", "t2");
当然,这不会解决超时的根本原因,但它会让您优雅地处理问题

感谢西格弗里德·戈施尔在


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

也有同样的问题。您必须关闭挡块中的运输。代码冻结的原因是,除非手动关闭smtp服务器连接,否则客户端的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();
    }
     }
 }
  • 禁用所有防病毒程序
  • 禁用防火墙
  • 然后试一试,如果你成功了,进一步调查以找到罪犯


    在我的例子中,它是防病毒的,我必须对
    SMTP
    上的出站邮件设置一个例外才能成功发送邮件。

    当您声明
    Transport.send()
    时,它将不起作用,请使用此选项而不是
    transport.sendMessage(message,message.getAllRecipients())
    并声明一个
    javax.mail.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 =
         "<!doctype html public \"-//w3c//dtd html 4.0 " +
         "transitional//en\">\n";
         out.println(docType +
         "<html>\n" +
         "<head><title>" + title + "</title></head>\n" +
         "<body bgcolor=\"#f0f0f0\">\n" +
         "<h1 align=\"center\">" + title + "</h1>\n" +
         "<p align=\"center\">" + res + "</p>\n" +
         "</body></html>");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
    }           
        }
    
    package org.java.vamsi;
    //导入javax.a
    
         <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.3</version>
        </dependency>
    
         <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.3</version>
        </dependency>