2010-10-27 49 views
1

我正在寫一些應用程序,我需要發送郵件。我的應用程序是在JAVA中,所以我可能會使用javamail。但我不知道如何使用它,以及如何從我的本地電腦配置郵件服務器,以便我可以測試郵件是否可以發送。請建議。我正嘗試在java中編寫簡單的郵件程序。我應該使用什麼。我如何配置我的本地機器發送郵件?

+0

我認識到GMAIL SMTP支付。有人可以提出一些免費的建議。 – 2010-10-27 17:23:45

回答

3

您還可以使用GMAIL smtp發送郵件。
下面是一個示例代碼段

String host = "smtp.gmail.com"; 
    String from = "username"; 
    String pass = "password"; 
    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 = {"[email protected]"}; // 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(); 
+0

對谷歌的任何依賴。我可以發送郵件到任何電子郵件地址嗎? – 2010-10-27 16:30:06

+0

@sushil bharwani,是的,你可以將它發送到任何有效的郵件地址,谷歌的服務器將得到使用。這是唯一的依賴 – 2010-10-27 16:31:26

+0

可以使用我的谷歌smtp服務器的生產級別的代碼。就像我用它發送20,000個員工的郵件一樣。對不起,如果我聽起來很愚蠢。 – 2010-10-27 16:36:17

相關問題