2009-08-17 45 views
0

在java中發送和接收郵件的最簡單方法是什麼?從java發送郵件

+0

http://stackoverflow.com/questions/561011/what-is-the-easiest-way-for-a-java-application-to-receive-incoming-email – rahul 2009-08-17 11:29:28

+0

http://stackoverflow.com/questions/848645 /發送電子郵件在java – rahul 2009-08-17 11:30:30

+1

定義「最簡單」。 – 2009-08-17 11:31:46

回答

10

不要忘記Jakarta Commons Email發送郵件。它有一個非常易於使用的API。

+0

+1。不知道它存在 – 2009-08-17 11:55:38

+0

這就是我正在尋找的.....謝謝.. .. .. .. .. – 2009-08-17 12:26:56

4

檢查this包裝出來。從鏈接,這裏有一個代碼示例:

Properties props = new Properties(); 
props.put("mail.smtp.host", "my-mail-server"); 
props.put("mail.from", "[email protected]"); 
Session session = Session.getInstance(props, null); 

try { 
    MimeMessage msg = new MimeMessage(session); 
    msg.setFrom(); 
    msg.setRecipients(Message.RecipientType.TO, 
         "[email protected]"); 
    msg.setSubject("JavaMail hello world example"); 
    msg.setSentDate(new Date()); 
    msg.setText("Hello, world!\n"); 
    Transport.send(msg); 
} catch (MessagingException mex) { 
    System.out.println("send failed, exception: " + mex); 
} 
7

JavaMail用來發送電子郵件(如每個人指出)傳統的答案。

因爲你也想收到郵件,但是,你應該檢查出Apache James。它是一個模塊化的郵件服務器,可以很好地配置。它會與POP和IMAP對話,支持自定義插件並可嵌入到您的應用程序中(如果您願意的話)。

1
try { 
Properties props = new Properties(); 
props.put("mail.smtp.host", "mail.server.com"); 
props.put("mail.smtp.auth","true"); 
props.put("mail.smtp.user", "[email protected]"); 
props.put("mail.smtp.port", "25"); 
props.put("mail.debug", "true"); 

Session session = Session.getDefaultInstance(props); 

MimeMessage msg = new MimeMessage(session); 

msg.setFrom(new InternetAddress("[email protected]")); 

InternetAddress addressTo = null; 
addressTo = new InternetAddress("[email protected]"); 
msg.setRecipient(javax.mail.Message.RecipientType.TO, addressTo); 

msg.setSubject("My Subject"); 
msg.setContent("My Message", "text/html; charset=iso-8859-9"); 

Transport t = session.getTransport("smtp"); 
t.connect("[email protected]", "password"); 
t.sendMessage(msg, msg.getAllRecipients()); 
t.close(); 
} catch(Exception exc) { 
    exc.printStackTrace(); 
}