Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java邮件gmail_Java_Email_Gmail - Fatal编程技术网

java邮件gmail

java邮件gmail,java,email,gmail,Java,Email,Gmail,我想通过google的smtp服务器在java程序中发送邮件,但它似乎无法发送邮件。有人能告诉我为什么吗 这是发送邮件的功能: public void sendMail(){ String from = "xxx@gmail.com"; String to = "xxx@hotmail.com"; String subject = "Test"; String message = "A test message"; SendMa

我想通过google的smtp服务器在java程序中发送邮件,但它似乎无法发送邮件。有人能告诉我为什么吗

这是发送邮件的功能:

     public void sendMail(){
            String from = "xxx@gmail.com";
    String to = "xxx@hotmail.com";
    String subject = "Test";
    String message = "A test message";

    SendMail sendMail = new SendMail(from, to, subject, message);
    sendMail.send();
}
这是我们的课

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;
}

public void send(){

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.setProperty( "mail.smtp.port", "587" );
    props.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getDefaultInstance(props);

    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(from, "MyPasswordGoesHere");
    }
      };

  try {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(text);

    Transport.send(message);
    System.out.println("message sent successfully");
    } catch (MessagingException e) {
    throw new RuntimeException(e);
     }
      }
        }

提前谢谢

好的,我用这个代码解决了这个问题:

年,我试着举例说明如何通过Gmail的SMTP服务器用Java发送电子邮件。这里有两个示例代码。其中一个使用Java Mail API,而另一个则利用Apache Commons邮件库。

?它会引起任何错误,还是会毫无怨言地结束?设置SMTP上的调试以查看客户端的操作。检查此项,可能会帮助您@我以它为例,它并没有结束,它只是挂在“Transport.send(message);line”上