How to override default unique boundary string and create our own boundary using MimeMultipart of JavaMail?

。_饼干妹妹 提交于 2019-12-07 07:40:10

问题


I have a web-app which I use which expects a specific boundary string like (“company mime boundary”).

I did not find a way to override the default behavior of MimeMultipart, when I do

Multipart mp = new MimeMultipart();

A unique boundary string is always created by the constructor and I want to override this behavior to have my own boundary string, but unable to do so as I did not find any API.

Even if I set it in content-type, it does not work and creates a unique boundary string always as the MimeMultipart is creating a default one.

mimeMsg.setHeader("Content-Type","multipart/mixed;boundary="company mime boundary");

Can anyone please suggest/help me on this.

How to override this default behavior ?


回答1:


From javax.mail.Multipart :

The mail.mime.multipart.ignoreexistingboundaryparameter System property may be set to true to cause any boundary to be ignored and instead search for a boundary line in the message

Try setting this property to true and then add your own using

mimeMsg.setHeader("Content-Type","");

I have not implemented it, but I am confident it can work

update

Try sub-classing the MimeMultipart class and overwrite the getBoundaryMethod(). See some sample code below:

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeMultipart;
public class MyMimeMultyPart extends MimeMultipart {
    /**
     * DataSource that provides our InputStream.
     */
    protected DataSource ds;

    /**
     * Indicates if the data has been parsed.
     */
    protected boolean parsed = true;

    private ContentType type;

    public MyMimeMultyPart(DataSource dataSource) throws MessagingException {
        super(dataSource);
    }

    public MyMimeMultyPart(String subtype) {
        type = new ContentType("multipart", subtype, null);
        type.setParameter("boundary", getBoundary());
        contentType = type.toString();
    }

    public MyMimeMultyPart() {
        super();
    }

    private static int part;

    private synchronized static String getBoundary() {
        int i;
        synchronized (MimeMultipart.class) {
            i = part++;
        }
        StringBuffer buf = new StringBuffer(64);
        buf.append("----=_Part_").append(i).append('_').append((new Object()).hashCode()).append('.').append(System.currentTimeMillis());
        return buf.toString();
    }
}


来源:https://stackoverflow.com/questions/13234024/how-to-override-default-unique-boundary-string-and-create-our-own-boundary-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!