2013-02-18 132 views
3

大家好我剛纔一直在試圖得到一些Java代碼來發送電子郵件到通過Gmail的Java用戶,這是我所:Java來通過Gmail發送電子郵件

@ManagedBean 
@ViewScoped 
public class email { 

    // Set up the SMTP server. 
    java.util.Properties props = new java.util.Properties(); 

    public void mail() { 
     System.out.println("Called mail"); 
     props.put(
       "mail.smtp.gmail", "smtp.gmail.com"); 
     props.put("mail.smtp.port", "587"); 

     Session session = Session.getDefaultInstance(props, null); 
// Construct the message 
     String to = "[email protected]"; 
     String from = "[email protected]"; 
     String subject = "Hello"; 
     Message msg = new MimeMessage(session); 


     try { 
      System.out.println("Setting up the email"); 
      msg.setFrom(new InternetAddress(from)); 
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
      System.out.println("here"); 

      msg.setSubject("Print Job"); 
      msg.setText("Hi,\n\nHow are you?"); 

      Transport.send(msg); 
      System.out.println("Sending message"); //does not get to this part 
     } catch (MessagingException e) { 
      // Error. 
     } 
    } 
} 

它沒有錯誤時運行等,我沒有得到控制檯中的發送消息,它只是在Transport.send(味精)它卡住了我做錯了什麼? gmail的設置都可以嗎?

編輯:

@ManagedBean 
@ViewScoped 
public class email { 

    // Set up the SMTP server. 
    java.util.Properties props = new java.util.Properties(); 

    public void mail() { 
     System.out.println("Called mail"); 
     String host = "smtp.gmail.com"; 
     String from = "------------"; 
     String pass = "----"; 

     props.put("mail.smtp.starttls.enable", "true"); // added this line 
     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"); 


     Session session = Session.getDefaultInstance(props, null); 
// Construct the message 
     String to = "--------"; 
     String subject = "Hello"; 
     Message msg = new MimeMessage(session); 


     try { 
      System.out.println("Setting up the email"); 
      msg.setFrom(new InternetAddress(from)); 
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
      System.out.println("here"); 

      msg.setSubject("Print Job"); 
      msg.setText("Hi,\n\nHow are you?"); 

      Transport.send(msg); 
      System.out.println("Sending message"); //does not get to this part 
     } catch (MessagingException e) { 
      // Error. 
     } 
    } 
} 

編輯: 試圖在提供給我一個鏈接的例子:

@ManagedBean 
@ViewScoped 
public class email { 

    // Set up the SMTP server. 
    public void mail() throws MessagingException { 
     String host = "smtp.gmail.com"; 
     String from = "------------"; 
     String pass = "------"; 
     Properties props = System.getProperties(); 
     props.put("mail.smtp.starttls.enable", "true"); // added this line 
     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 = {"-----------"}; // added this line 

     Session session = Session.getDefaultInstance(props, null); 
     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++) { // changed from a while loop 
      toAddress[i] = new InternetAddress(to[i]); 
     } 
     System.out.println(Message.RecipientType.TO); 

     for (int i = 0; i < toAddress.length; i++) { // changed from a while loop 
      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(); 
    } 
} 

,這是拋出了這個錯誤:

INFO: To 
WARNING: #{email.mail()}: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25; 
    nested exception is: 
    java.net.ConnectException: Connection timed out: connect 
javax.faces.FacesException: #{email.mail()}: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25; 
    nested exception is: 
    java.net.ConnectException: Connection timed out: connect 
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) 
    at javax.faces.component.UICommand.broadcast(UICommand.java:315) 
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) 
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) 
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) 
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) 
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) 
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) 
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) 
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655) 
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161) 
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231) 
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317) 
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195) 
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860) 
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757) 
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056) 
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229) 
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) 
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) 
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) 
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) 
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) 
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) 
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71) 
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) 
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) 
    at java.lang.Thread.run(Thread.java:722) 
Caused by: javax.faces.el.EvaluationException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25; 
    nested exception is: 
    java.net.ConnectException: Connection timed out: connect 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) 
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) 
    ... 36 more 
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25; 
    nested exception is: 
    java.net.ConnectException: Connection timed out: connect 
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934) 
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638) 
    at javax.mail.Service.connect(Service.java:295) 
    at javax.mail.Service.connect(Service.java:176) 
    at richard.fileupload.email.mail(email.java:101) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:601) 
    at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779) 
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:528) 
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257) 
    at com.sun.el.parser.AstValue.invoke(AstValue.java:248) 
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302) 
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39) 
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50) 
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) 
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) 
    ... 37 more 
Caused by: java.net.ConnectException: Connection timed out: connect 
    at java.net.DualStackPlainSocketImpl.connect0(Native Method) 
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69) 
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) 
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) 
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) 
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157) 
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391) 
    at java.net.Socket.connect(Socket.java:579) 
    at java.net.Socket.connect(Socket.java:528) 
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288) 
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231) 
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900) 
    ... 54 more 
+1

'mail.smtp.gmail'不是JavaMail的識別性能。和你的代碼的其他問題。有關如何通過Gmail服務器從Java發送郵件的工作示例,請參閱[這裏](http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/)。 – Perception 2013-02-18 15:26:30

+0

我認爲你應該用你創造的道具實際創建一個運輸實例。 – user 2013-02-18 15:35:25

+1

[如何通過Java應用程序使用Gmail/Yahoo/Hotmail發送電子郵件](http://stackoverflow.com/questions/46663/how-to-send-an-email-by-java-application-using -gmail-yahoo-hotmail) – andyb 2013-02-18 15:35:50

回答

4

我認爲你需要使用端口,SMTPS(不SMTP)運輸。

從一個開源項目,一個完整的可行代碼:

http://jstock.hg.sourceforge.net/hgweb/jstock/jstock/file/d9290c44d19c/src/org/yccheok/jstock/alert/GoogleMail.java

/** 
* Send email using GMail SMTP server. 
* 
* @param username GMail username 
* @param password GMail password 
* @param recipientEmail TO recipient 
* @param ccEmail CC recipient. Can be empty if there is no CC recipient 
* @param title title of the message 
* @param message message to be sent 
* @throws AddressException if the email address parse failed 
* @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage 
*/ 
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { 
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 

    // Get a Properties object 
    Properties props = System.getProperties(); 
    props.setProperty("mail.smtps.host", "smtp.gmail.com"); 
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); 
    props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
    props.setProperty("mail.smtp.port", "465"); 
    props.setProperty("mail.smtp.socketFactory.port", "465"); 
    props.setProperty("mail.smtps.auth", "true"); 

    /* 
    If set to false, the QUIT command is sent and the connection is immediately closed. If set 
    to true (the default), causes the transport to wait for the response to the QUIT command. 

    ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html 
      http://forum.java.sun.com/thread.jspa?threadID=5205249 
      smtpsend.java - demo program from javamail 
    */ 
    props.put("mail.smtps.quitwait", "false"); 

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

    // -- Create a new message -- 
    final MimeMessage msg = new MimeMessage(session); 

    // -- Set the FROM and TO fields -- 
    msg.setFrom(new InternetAddress(username + "@gmail.com")); 
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); 

    if (ccEmail.length() > 0) { 
     msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); 
    } 

    msg.setSubject(title); 
    msg.setText(message, "utf-8"); 
    msg.setSentDate(new Date()); 

    SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); 

    t.connect("smtp.gmail.com", username, password); 
    t.sendMessage(msg, msg.getAllRecipients());  
    t.close(); 
} 
+0

@Cheok ...試試這個,但有連接異常 - javax.mail .MessagingException:無法連接到SMTP主機:smtp.gmail.com,端口:465; – Leo 2014-12-04 08:54:48

0
props.put("mail.smtp.port", "587"); 

嘗試更改以上代碼爲:

props.put("mail.smtp.port", "465"); 

javax.mail.Authenticator();您的問題在哪裏?

0

嘗試與交通運輸做到這一點:

final Transport transport = session.getTransport("smtp"); 
    transport.connect(host, from, pass); 
    transport.sendMessage(msg, msg.getAllRecipients()); 
    transport.close(); 
+0

感謝仍然不工作:(,沒有日誌錯誤 – user2065929 2013-02-18 15:58:26

+0

@ user2065929沒有代碼給出任何例外嗎?您使用完整的電子郵件作爲用戶名(從)? – Alepac 2013-02-18 16:02:03

+0

是的我使用完整的電子郵件作爲用戶名,並沒有任何例外,在控制檯或任何東西,嘗試了一個新的代碼片段,但它是拋出一個錯誤 – user2065929 2013-02-18 16:05:16

0

試試這個代碼。它完全是工作...

package my.test.service; 
import java.util.Properties; 
import javax.mail.Authenticator; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Message; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
public class Sample { 
    public static void main(String args[]) { 
     final String SMTP_HOST = "smtp.gmail.com"; 
     final String SMTP_PORT = "587"; 
     final String GMAIL_USERNAME = "[email protected]"; 
     final String GMAIL_PASSWORD = "xxxxxxxxxx"; 

     System.out.println("Process Started"); 

     Properties prop = System.getProperties(); 
     prop.setProperty("mail.smtp.starttls.enable", "true"); 
     prop.setProperty("mail.smtp.host", SMTP_HOST); 
     prop.setProperty("mail.smtp.user", GMAIL_USERNAME); 
     prop.setProperty("mail.smtp.password", GMAIL_PASSWORD); 
     prop.setProperty("mail.smtp.port", SMTP_PORT); 
     prop.setProperty("mail.smtp.auth", "true"); 
     System.out.println("Props : " + prop); 

     Session session = Session.getInstance(prop, new Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(GMAIL_USERNAME, 
         GMAIL_PASSWORD); 
      } 
     }); 

     System.out.println("Got Session : " + session); 

     MimeMessage message = new MimeMessage(session); 
     try { 
      System.out.println("before sending"); 
      message.setFrom(new InternetAddress(GMAIL_USERNAME)); 
      message.addRecipients(Message.RecipientType.TO, 
        InternetAddress.parse(GMAIL_USERNAME)); 
      message.setSubject("My First Email Attempt from Java"); 
      message.setText("Hi, This mail came from Java Application."); 
      message.setRecipients(Message.RecipientType.TO, 
        InternetAddress.parse(GMAIL_USERNAME)); 
      Transport transport = session.getTransport("smtp"); 
      System.out.println("Got Transport" + transport); 
      transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD); 
      transport.sendMessage(message, message.getAllRecipients()); 
      System.out.println("message Object : " + message); 
      System.out.println("Email Sent Successfully"); 
     } catch (AddressException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (MessagingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
0
import java.util.Properties; 

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

public class MessageSender { 

    public static void sendHardCoded() throws AddressException, MessagingException { 
     String to = "[email protected]"; 
     final String from = "[email protected]"; 

     Properties properties = new Properties(); 
     properties.put("mail.smtp.starttls.enable", "true"); 
     properties.put("mail.smtp.auth", "true"); 
     properties.put("mail.smtp.host", "smtp.gmail.com"); 
     properties.put("mail.smtp.port", "587"); 

     Session session = Session.getInstance(properties, 
       new javax.mail.Authenticator() { 
        protected PasswordAuthentication getPasswordAuthentication() { 
         return new PasswordAuthentication(from, "BeNice"); 
        } 
       }); 

     MimeMessage message = new MimeMessage(session); 
     message.setFrom(new InternetAddress(from)); 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
     message.setSubject("Hello"); 
     message.setText("What's up?"); 

     Transport.send(message); 
    } 

} 
相關問題