Javamail回复删除或修改message-id标头

时间:2013-05-20 05:31:41

标签: java javamail

我想在使用Javamail回复电子邮件时修改或删除“Message-ID”标头。经过一些研究后我发现我需要创建一个扩展MimeMessage的自定义类。这是我创建的课程。

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

class MyMessage extends MimeMessage
{

    public MyMessage(Session session)
    {
        super(session);
    }

    @Override
    protected void updateMessageID() throws MessagingException {
        removeHeader("Message-Id");
    }

}

以下代码与获取消息有关

public List<EmailSenderInfo> checkEmail() throws Exception
{
    String host = "HOST";
    String username = "MYUSERNAME";
    String password = "MYPASS";

    List<EmailSenderInfo> emailSenderList = new ArrayList<EmailSenderInfo>();

    Properties properties = System.getProperties();
    properties.setProperty("mail.store.protocol", "imaps");
    Session session = Session.getDefaultInstance(properties);

    Store store = session.getStore("imaps");
    store.connect(host, username, password);

    /*
     * Folder[] f = store.getDefaultFolder().list(); for (Folder fd : f)
     * System.out.println(">> " + fd.getName());
     */
    Folder folder = store.getFolder("INBOX");

    if (!folder.exists())
    {
        System.out.println("No INBOX...");
        System.exit(0);
    }
    folder.open(Folder.READ_WRITE);
    Message[] msg = folder.getMessages();

    if (msg.length < 1)
    {
        System.out.println("No new messages!");
        throw new Exception("No new messages!");
    }

    for (int i = 0; i < msg.length; i++)
    {
        if (!msg[i].isSet(Flag.SEEN))
        {
            EmailSenderInfo emailSenderInfo = new EmailSenderInfo();
            emailSenderInfo.message = msg[i];
            System.out.println("------------ Message " + (i + 1) + " ------------");

            // String from = InternetAddress.toString(msg[i].getFrom());
            Address[] fromArray = msg[i].getFrom();
            InternetAddress fromInternetAddress = (InternetAddress) fromArray[0];
            String from = fromInternetAddress.getAddress();
            String fromName = fromInternetAddress.getPersonal();

            if (fromName != null)
            {
                emailSenderInfo.fromName = fromName;
            }

            if (from != null)
            {
                // System.out.println("From: " + from);
                emailSenderInfo.from = from;
            }

            // String replyTo = InternetAddress.toString(msg[i].getReplyTo());
            Address[] replyToArray = msg[i].getFrom();
            InternetAddress ReplyToInternetAddress = (InternetAddress) replyToArray[0];
            String replyTo = ReplyToInternetAddress.getAddress();
            String replyToName = ReplyToInternetAddress.getPersonal();

            if (replyTo != null)
            {
                // System.out.println("Reply-to: " + replyTo);
                emailSenderInfo.replyTo = replyTo;
            }

            if (replyToName != null)
            {
                // System.out.println("Reply-to: " + replyTo);
                emailSenderInfo.replyToName = replyToName;
            }

            String to = InternetAddress.toString(msg[i].getRecipients(Message.RecipientType.TO));
            if (to != null)
            {
                // System.out.println("To: " + to);
                emailSenderInfo.to = to;
            }

            String subject = msg[i].getSubject();
            if (subject != null)
            {
                // System.out.println("Subject: " + subject);
                emailSenderInfo.subject = subject;
            }

            Date sentDate = msg[i].getSentDate();
            if (sentDate != null)
            {
                System.out.println("Sent: " + sentDate);
                emailSenderInfo.sentDate = sentDate;
            }

            String bodyHtml = "";

            // get content
            Multipart multipart = (Multipart) msg[i].getContent();
            for (int x = 0; x < multipart.getCount(); x++)
            {

                BodyPart bodyPart = multipart.getBodyPart(x);

                String disposition = bodyPart.getDisposition();

                if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))
                {
                    // dealing with attachments only
                    System.out.println("Mail has some attachment : ");
                    DataHandler handler = bodyPart.getDataHandler();
                    System.out.println("file name : " + handler.getName());
                    System.out.println("ddddd: " + bodyPart.getContent().toString());
                }
                else
                {
                    String classType = bodyPart.getContent().getClass().toString();

                    if (classType.contains("java.lang.String"))
                    {
                        bodyHtml = bodyPart.getContent().toString();
                    }
                    else if (classType.contains("javax.mail.internet.MimeMultipart"))
                    {
                        MimeMultipart bodyContent = (MimeMultipart) bodyPart.getContent();
                        for (int b = 0; b < bodyContent.getCount(); b++)
                        {
                            IMAPBodyPart imapBody = (IMAPBodyPart) bodyContent.getBodyPart(b);
                            System.out.println("1: " + imapBody.getContent());
                            bodyHtml = imapBody.getContent().toString();
                            // System.out.println("2: " + bodyContent.getBodyPart(b));
                            // System.out.println("3: " + bodyPart.getContent().toString());
                        }
                    }
                }
                emailSenderInfo.bodyHtml = bodyHtml;
            }


            MyMessage reply = (MyMessage) msg[i].reply(false);
            emailSenderInfo.reply = reply;
            // reply.setFrom(msg[i].getFrom()[0]);
            MimeMessage orig = (MimeMessage) msg[i];
            StringBuffer buffer = new StringBuffer("Thanks\n\n");
            if (orig.isMimeType("text/plain"))
            {
                String content = (String) orig.getContent();
                StringReader contentReader = new StringReader(content);
                BufferedReader br = new BufferedReader(contentReader);
                String contentLine;
                while ((contentLine = br.readLine()) != null)
                {
                    buffer.append("> ");
                    buffer.append(contentLine);
                    buffer.append("\r\n");
                }
            }
            // Set the reply content
            // reply.setText(buffer.toString());
            // emailSenderInfo.reply = reply;

            emailSenderList.add(emailSenderInfo);
            // System.out.println();
        }// end if unread
    }
    folder.close(true);
    store.close();

    return emailSenderList;
}

我的程序中有两种方法。其中一个检查邮件,另一个检查回复电子邮件。

Message reply = msg[i].reply(false);

“reply”与其他参数一起传递给此方法。

public void sendReply(String from, String replyTo, Message reply, String messageReply, Boolean attachment) throws Exception
{
    String host = "MYHOST";
    String username = "MYUSERNAME";
    String pass = "MYPASSWORD";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true"); // added this line
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);

    MimeMessage mimeReply = (MimeMessage) reply;
    mimeReply.setFrom((Address) InternetAddress.parse(from)[0]);        

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(messageReply, "text/html");

    Multipart multipart = new MimeMultipart();
    // Set text message part
    multipart.addBodyPart(messageBodyPart);

    if (attachment)
    {
        messageBodyPart = new MimeBodyPart();
        String filename = "test.jpg";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
    }

    mimeReply.setContent(multipart);

    Transport transport = session.getTransport("smtp");
    transport.connect(host, username, pass);
    transport.sendMessage(mimeReply, InternetAddress.parse(replyTo));
    transport.close();
    System.out.println("Message Sent!");
}

我必须使用MyMessage类才能删除“Message-ID”标头。我试过以下

MyMessage mimeReply = (MyMessage) reply;

但是我在运行时遇到以下错误

java.lang.ClassCastException: javax.mail.internet.MimeMessage cannot be cast to javamailer.MyMessage

如何使用“MyMessage”类,以便我可以使用回复消息删除“Message-ID”标题?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

回复电子邮件时:

创建消息时,现在它应该是:

MimeMessage msg = new MimeMessage(session);

将其更改为,

MyMessage msg = new MyMessage(session);

当检查电子邮件时,您不需要删除标题,因为该邮件已经在邮箱中,我认为您需要做的是在该实例上回复邮件时为名称邮件实例化,例如:

 MyMessage msg = new MyMessage(session);
 msg.updateMessageID();

由于您使用的是对现有消息的引用:

您可以执行以下操作:

创建一个新的构造函数:

public MyMessage (MimeMessage message) {
     super(message);
}

回复时:

 MyMessage mimeReply = new MyMessage(reply);
 mimeReply.updateMessageID();

然后发送mimeReply NOT回复。