2015-08-17 56 views
2

我試圖使用NetBeans中的JavaMail的功能,但不斷收到錯誤在NetBeans錯誤使用JavaMail

javax.mail.MessagingException: Could not connect to SMTP host: 10.101.3.229, port: 25; 
nested exception is: 
java.net.ConnectException: Connection timed out: connect 

我使用的代碼是:

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class TESTINGemail { 

public static void main(String [] args) 
{  
    String to = "[email protected]"; 
    String from = "[email protected]"; 

    String host = "localhost"; 

    Properties properties = System.getProperties(); 

    properties.setProperty("mail.smtp.host", host); 

    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("This is the Subject Line!"); 

    message.setText("This is actual message"); 

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

我使用的教程,這基本上是他們使用的代碼。我試圖改變主機,但每次都失敗。

+0

JavaMail常見問題[調試連接問題的提示](http://www.oracle.com/technetwork/java/javamail/faq/index.html#condebug)。 –

回答

2

如果您使用gmail id發送郵件,您必須使用gmail主機服務器地址'mail.smtp.host',那麼您不能使用本地主機。

import java.util.Properties; 
import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

public class MailSender { 
    public static void send (String to,String message1,String subject,String ss) 
     throws Exception { 
    String host ="smtp.gmail.com"; 
    String from="[email protected]"; 
    String password="Your password"; 
    Properties props = System.getProperties(); 

    props.put("mail.transport.protocol", "smtps"); 
    props.put("mail.smtp.user", from); 
    props.put("mail.smtp.password", password); 
    props.put("mail.smtp.port", "465"); 
    props.put("mail.smtps.auth", "true"); 
    props.put("mail.smtp.starttls.enable","true"); 

    props.put("mail.smtp.host", host); 

    Session session = Session.getInstance(props, null); 


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



    Transport transport = session.getTransport("smtps"); 
    transport.connect(host,from, password); 
    transport.sendMessage(message, message.getAllRecipients()); 
    System.out.println("mail has been sent"); 
} 


    public static void main(String arg[]) throws Exception 
    { 

     MailSender m=new MailSender(); 
     m.send("[email protected]", "hello ..", "test mail...",""); 
    } 
    } 

,並停用你的PC殺毒軟件和防火牆都還打開「訪問不夠安全的應用」在谷歌帳戶設置。

https://www.google.com/settings/security/lesssecureapps