2014-02-10 83 views
1

嗨,我想通過下面的代碼幫助從Outlook 2010發送電子郵件。使用java郵件API從Outlook 2010發送郵件

package javamail; 

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

public class JavaMailTest { 
    public static void main(String[] args) { 
     String host="host"; 
     final String user="[email protected]";//change accordingly 
     String to="[email protected]";//change accordingly 

     //Get the session object 
     Properties props = new Properties(); 
     props.put("mail.smtp.host",host); 
     props.put("mail.smtp.auth", "false"); 

     Session session=Session.getDefaultInstance(props, null); 
     session.setDebug(true); 

     //Compose the message 
     try { 
      MimeMessage message = new MimeMessage(session); 
      message.saveChanges(); 
      message.setFrom(new InternetAddress(user)); 
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); 
      message.setSubject("Test mail"); 
      message.setText("This is test mail."); 

      //send the message 
      Transport.send(message); 

      System.out.println("message sent successfully..."); 
     } 
     catch (MessagingException e) {e.printStackTrace();} 

    } 
} 

上面的代碼工作正常,我可以發送郵件(在我的技術管理員啓用中繼服務器後)。但問題是我無法在我的Outlook中看到發送的郵件。在分析我發現,Java郵件API直接從SMTP服務器發送郵件。但是我希望郵件從我的outlook profile發送,即我應該能夠在我的發送郵件文件夾中看到它。我應該怎麼做?什麼API或第三方開放源碼庫可以用來實現這一目標?

+0

有你看過任何VBA/Office腳本? – admdrew

+0

@admdrew什麼是VBA/Office腳本?它與視覺基本相關嗎?不,我不知道上面的腳本語言..最好我想在java中的一些解決方案。 –

+0

什麼是VBA/Office腳本?請繼續往下看!你也可以使用標準的.NET來做到這一點;我會建議只做一些額外的研究。 – admdrew

回答

1

如果您希望將郵件複製到已發送的文件夾以及發送,您需要將其明確複製到那裏。

Transport.send(msg); 
Folder sent = store.getFolder("Sent"); 
sent.appendMessages(new Message[] { msg }); 
+0

應使用哪種商店類型。我曾嘗試使用Store store = session.getStore(「smtp」);但它是拋出異常爲javax.mail.NoSuchProviderException:無效的提供程序。應使用哪種商店類型? –

+0

「smtp」不是Store協議,它是一種傳輸協議。使用「imap」或「pop3」訪問您的服務器。 –

0

運行代碼時出現以下錯誤。

com.sun.mail.util.MailConnectException: 

Couldn't connect to host, port: host, 25; timeout -1; 
nested exception is: java.net.UnknownHostException: host 
+0

你需要幫助運行上面的代碼,那麼你需要添加一個評論,而不是張貼爲答案 –

0

使用可以試試下面代碼.. 它爲我工作的Outlook ..

String host = "outlook.office365.com"; 
    Properties props = new Properties(); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", host);  //  mail server host 
    props.put("mail.smtp.port", "587");  // port 
0

嘗試下面的代碼,郵件存儲到發件箱的Outlook ...

 Store store = session.getStore("imaps"); 
     store.connect("imap-mail.outlook.com", "username", "password"); 
     Folder folder = store.getFolder("Sent Items"); 
     folder.open(Folder.READ_WRITE); 
     message.setFlag(Flag.SEEN, true); 
     folder.appendMessages(new Message[] {message}); 
     store.close(); 
相關問題