简体   繁体   中英

Save Sent email to sent items folder using javax mail

public static void sendEmail(String msgHeader, String msg, String emailId, String emailFrom) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "false");
    props.put("mail.debug", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailServer);
    props.put("mail.smtp.port", port#);
    props.put("mail.smtp.auth.mechanisms", "NTLM");
    props.put("mail.smtp.auth.ntlm.domain", domainName);

    Session session = Session.getDefaultInstance(props, null);
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailFrom));
        to = emailId;
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(msgHeader);

        message.setText(msg, "utf-8", "html");

        message.saveChanges();
        session.getDebug();
        Transport.send(message);
        // Copy message to "Sent Items" folder as read
        Store store = session.getStore("ntlm");
        store.connect(mailServer, emailFrom, pwd);
        Folder folder = store.getFolder("Sent Items");
        folder.open(Folder.READ_WRITE);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] {message});
        store.close();
    } catch (Exception ex) {
        logger.error("Error occured while sending Email !", ex);
    }
}

When I try to execute the code above, i am able to send out the emails. the issue is with saving the email. I get an error (NoSuchProviderException) at the line Store store = session.getStore("ntlm");

I have a few questions on this:-

  1. The email sending part works without password verification with ntlm. Is it possible to save the sent email into the sent items folder without password verification. If yes then how?
  2. session.getStore doesnt work when i use a. smtp - exception (Invalid provider) b. ntlm - exception (NoSuchProviderException) what should i use here.

Thanks in advance for your help.

"ntlm" is not a type of Store, it's an authentication mechanism. The store types supported by JavaMail are "imap" and "pop3". You almost certainly want "imap". Just like sending, you're going to need to supply your username and password when connecting to your imap server.

Also, upgrade to the current version of JavaMail if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM