2012-10-25 59 views
-1

我想使用Gmail smtp服務器發送郵件。使用Gmail Smtp發送郵件時出現異常?

package com; 

import java.util.Properties; 

import javax.mail.Message; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 

public class Email { 
public static void main(String[] args) { 
    try 
    { 
    String host = "smtp.gmail.com"; 
    final String from = "[email protected]"; 
    final String pass = "mypassword"; 
    Properties props = System.getProperties(); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", host); 
    props.put("mail.smtp.user", from); 
    props.put("mail.smtp.password", pass); 
    props.put("mail.smtp.port", "587"); 
    props.put("mail.smtp.auth", "true"); 

    String[] to = {"[email protected]"}; 

    Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(from, pass); 
      } 
      }); 
    MimeMessage message = new MimeMessage(session); 
    message.setFrom(new InternetAddress(from)); 

    InternetAddress[] toAddress = new InternetAddress[to.length]; 

    // To get the array of addresses 
    for(int i=0; i < to.length; i++) { 
     toAddress[i] = new InternetAddress(to[i]); 
    } 
    System.out.println(Message.RecipientType.TO); 

    for(int i=0; i < toAddress.length; i++) { 
     message.addRecipient(Message.RecipientType.TO, toAddress[i]); 
    } 
    message.setSubject("sending in a group"); 
    message.setText("Welcome to JavaMail"); 
    Transport transport = session.getTransport("smtp"); 
    transport.connect(host, from, pass); 
    transport.sendMessage(message, message.getAllRecipients()); 
    transport.close(); 
    }catch (Exception e) { 
     System.out.println(e); 
    } 
} 
} 

但我得到一個exception

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; 
    nested exception is: 
    java.net.ConnectException: Connection refused: connect 

如何刪除這個錯誤? 在此先感謝。

+0

重複的也許此http://stackoverflow.com/questions/1990454/using-javamail-to-connect-to-gmail-smtp-server-ignores-specified-port-and-tries – tartak

+1

實際上,你可以連接到smtp.gmail.com 587?試試'telnet smtp.gmail.com 587'?防火牆規則可能會阻止連接。 – beny23

+0

端口號是465 –

回答

0

我認爲問題出在我的電子郵件ID中。 我創建了一個新的,它正在工作。

謝謝大家。

1

更簡單的選擇是使用apache commons郵件。

import org.apache.commons.mail.*; 

Email email = new SimpleEmail(); 
email.setHostName("smtp.googlemail.com"); 
email.setSmtpPort(465); 
email.setAuthenticator(new DefaultAuthenticator("username", "password")); 
email.setSSL(true); 
try{ 
email.setFrom("[email protected]"); 
email.setSubject("hello"); 
String s="hi" 
email.setMsg(s); 
email.addTo(id); 
email.send(); 
相關問題