2014-02-10 47 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();