使用java mail api从outlook 2010发送邮件

时间:2014-02-10 15:46:39

标签: java email outlook javamail outlook-2010

您好我正在尝试使用以下代码从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="username@domain.com";//change accordingly  
        String to="username@domain.com";//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();}

    }
}

上面的代码工作正常,我能够发送邮件(在我的技术管理员启用服务器上的中继后)。但问题是我无法在我的展望中看到发送的邮件。在分析中我发现java mail api直接从smtp服务器发送邮件。但我希望邮件从我的Outlook配置文件发送,即我应该能够在我发送的邮件文件夹中看到它。我该怎么办?可以用什么api或第三方开源库来实现这个目标?

4 个答案:

答案 0 :(得分:1)

如果您希望将邮件复制到“已发送”文件夹以及发送邮件,则需要在此处明确复制邮件。

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

答案 1 :(得分:0)

运行代码时出现以下错误。

com.sun.mail.util.MailConnectException:

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

答案 2 :(得分: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

答案 3 :(得分:0)

尝试将邮件存储到Outlook的sendbox中。

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();