簡體   English   中英

使用Java Mail API從Outlook 2010發送郵件

[英]Send mail from outlook 2010 using java mail 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="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();}

    }
}

上面的代碼正常工作,並且我能夠發送郵件(在我的技術管理員啟用了服務器中繼功能之后)。 但是問題是我無法在我的Outlook中看到已發送的郵件。 經過分析,我發現java郵件api直接從smtp服務器發送郵件。 但是我希望郵件從我的Outlook配置文件發送,即我應該能夠在我的已發送郵件文件夾中看到它。 我該怎么辦? 可以使用什么api或3rd party開源庫來實現此目的?

如果您希望將郵件復制到“已發送”文件夾中並進行發送,則需要在此顯式復制它。

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

嘗試將郵件存儲到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();

運行代碼時遇到錯誤。

com.sun.mail.util.MailConnectException:

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

嘗試這個。 它適用於我的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM