2013-02-10 35 views

回答

2

您需要查看JavaMail API,並且由於PHP的mail()需要,它需要一個SMTP服務器來發送該電子郵件。

如果您需要SMTP服務器,建議您在Google上搜索適用於您的操作系統的SMTP服務器,或者您可以使用ISP或服務器主機提供的SMTP服務器。

+0

我不能只使用SMTP發送郵件。我需要一些類似於PHP的機制,它使用sendmail系統發送郵件。 – J33nn 2013-02-10 23:28:13

+2

但是PHP的mail()確實使用了SMTP。 – 2013-02-10 23:31:42

+0

您能告訴我哪裏可以找到PHP郵件功能使用的STMP配置嗎?這是在php.ini文件中配置的權利? – J33nn 2013-02-10 23:36:51

5

Java Mail API支持發送和接收電子郵件。該API提供了一種插件架構,供應商可以在運行時動態發現和使用其專有協議的實施。 Sun提供的參考實現和其支持以下協議:

  • 互聯網郵件訪問協議(IMAP)
  • 簡單郵件傳輸協議(SMTP)
  • 郵局協議3(POP 3)

下面是如何使用它的一個例子:

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 static void main(String[] args) { 

      String from = "[email protected]"; 
      String to = "[email protected]"; 
      String subject = "Test"; 
      String message = "A test message"; 
      SendMail sendMail = new SendMail(from, to, subject, message); 
      sendMail.send(); 
    } 

    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) { 
      e.printStackTrace(); 
     } 

     try { 
      simpleMessage.setFrom(fromAddress); 
      simpleMessage.setRecipient(RecipientType.TO, toAddress); 
      simpleMessage.setSubject(subject); 
      simpleMessage.setText(text);  
      Transport.send(simpleMessage); 
     } catch (MessagingException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

這很好,但我不能使用SMTP服務器發送郵件,因爲沒有可用的。但仍然可以使用PHP的mail()方法,它使用系統sendmail從應用程序傳遞郵件。我正在尋找類似的東西。 – J33nn 2013-02-10 23:27:35

+1

PHP'mail()'確實使用SMTP。 – syb0rg 2013-02-10 23:34:35

+0

@ syb0rg我可以使用此代碼來欺騙郵件嗎? – Prakhar 2013-08-09 09:22:10

0

您可以使用JavaMail API與本地像Apache James SMTP服務器,因此安裝和運行James服務器後,您可以在SMTP服務器IP設置爲127.0.0.1

0

我應該使用相同/相似的機制,如PHP的郵件()使用。

你不能,因爲它不存在。如果這是要求,那就改變它。

不幸的是,我不知道該怎麼做。

請參閱JavaMail API。

相關問題