Javamail API如何保存已发送的味精

时间:2018-08-28 16:13:47

标签: java automation javamail

我正在尝试将电子邮件从acc1发送到acc2。该代码似乎可以正常工作,我可以在acc2上找到我的邮件。但是我在acc1的“已发送”文件夹中找不到它。 (我以yandex为例)。

我尝试使用imap协议并将其保存下来,但是代码没有任何异常就结束了,但是在发送中仍然找不到消息。

我的代码:

public class sendMail {
    public static void main(String[] args) {
        String to = "TO_ACC";         // sender email
        String from = "FROM_ACC";       // receiver email

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", "smtp.yandex.ru");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.port", "465");
        properties.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(properties,new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("FROM_ACC","FROM_PASS");
            }
        }); // default session

        try {
            MimeMessage message = new MimeMessage(session); // email message

            message.setFrom(new InternetAddress(from)); // setting header fields

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.addRecipient(Message.RecipientType.CC, new InternetAddress(to));
            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(to));

            message.setSubject("new hjhjh"); // subject line

            // actual mail body
            message.setText("some kjkjk");

            // Send message
            Transport.send(message); System.out.println("Email Sent successfully....");

            //Copy in sent

            Store store = session.getStore("imap");

            store.connect("imap.yandex.ru",993,"FROM_ACC","FROM_PASS" );
            Folder folder = store.getFolder("Sent");
            folder.open(Folder.READ_WRITE);
            message.setFlag(Flags.Flag.SEEN, true);
            folder.appendMessages(new Message[] {message});
            store.close();
        } catch (MessagingException mex){ mex.printStackTrace(); }
    }

1 个答案:

答案 0 :(得分:0)

只是将 Store store = session.getStore("imap");更改为Store store = session.getStore("imaps");

还添加了一个新属性

 properties.setProperty("mail.imap.starttls.enable", "true");