2012-09-28 51 views
0

为什么此代码不能发送电子邮件?没有错误,它只是不发送。使用java应用程序发送电子邮件

package tips.mails; 

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.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 



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.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); 
    } catch (MessagingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

    public static void main(String args[]) 
    { 
     new SendMail("source", "dist","Subject", "Test Message!!!"); 
    } 
} 
+2

你有没有真正调用过send()? – David

+1

如果没有例外,邮件服务器上会发生什么?你有没有调试过?把它指向你可以控制的邮件服务器(类似Smtp4Dev或类似的东西)并观察邮件服务器日志。也许服务器拒绝它?也许收件人将其标记为垃圾邮件?如果问题的本质是“我运行这个代码并且我的收件箱没有收到新消息”,那么有许多东西可能会出错,其中大部分与代码无关。 – David

+0

什么是你的send()方法?..是不是要暗示??:P – PermGenError

回答

3

您实例化一个SendMail对象,并对它做任何事情。也许你也应该执行你的send()方法。

1

你忘了打电话给发送。试试这个

new SendMail("source", "dist","Subject", "Test Message!!!").send(); 
+0

javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,端口:465,响应: -1 \t在com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1270) \t在com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370) \t在javax.mail .Service.connect(Service.java:275) \t在javax.mail.Service.connect(Service.java:156) \t在javax.mail.Service.connect(Service.java:105) \t在的javax。 mail.Transport.send0(Transport.java:168) \t at ja vax.mail.Transport.send(Transport.java:98) \t at tips.mails.SendMail.send(SendMail.java:53) \t at tips.mails.SendMail.main(SendMail.java:63) – user1625324

+0

check你的服务器的主机名和端口是否正确.. – Anand

+0

其运行只与端口为25的me.com服务器如何使它运行于所有服务器 – user1625324

相关问题