JavaMail: send message copying it to Sent Items folder


import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.Flags.Flag;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public final class MailIMAP {
  
  // Email server properties
  private static String host = "mailserver.com";
  private static String user = "user";
  private static String pass = "pass";
  
  // IMAP properties
  private static String imapProtocol = "imap";
  // Unfortunately there is no way to know sent folder name using Java code, 
  // so it must be specified as a property
  private static String folderName = "Sent Items";
  
  // Message accounts
  private static String fromAccount = "someone@mailserver.com";
  private static String toAccount = "anotherone@mailserver.com";
  
  /**
   *  User/password authenticator 
   */
  private static class MailAuthenticator extends Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(user, pass);
      }
  }
 
  /**
   * Send mail and copy it to "Sent Items" folder
   * @param args
   * @throws Exception
   */
  public static void main(String [] args) throws Exception {
 
    // Java Mail properties
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");
    
    // Mail session authentified
    Session session = Session.getInstance(props, new MailAuthenticator());
    
    // Send message
    Message message = new MimeMessage(session);
    message.setSubject("Test");
    message.setFrom(new InternetAddress(fromAccount));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAccount));
    message.setText("Body text");
    Transport.send(message);
    
    // Copy message to "Sent Items" folder as read
    Store store = session.getStore(imapProtocol);
    store.connect(host, user, pass);
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_WRITE);
    message.setFlag(Flag.SEEN, true);
    folder.appendMessages(new Message[] {message});
    store.close();
    
  }
 
}