1. 程式人生 > >Java傳送內嵌圖片的郵件

Java傳送內嵌圖片的郵件

使用Java傳送郵件時,既需要傳送html文件又需要在郵件中內嵌圖片(非附件形式),這裡封裝了一個類使用JavaMail組織的郵件傳送,支援多張圖片傳送,並指定圖片位置。注意img標籤src要如下寫<img src=\"cid:abcd\">"其中abcd對應mageMailDto#imageCid,可以自行定義,不要出現重複。

傳送方法,注意替換幾個郵件引數,如host、user、password

 /**
     * 傳送內嵌圖片的郵件
     *
     * @param fromEmailAddress   發件人郵箱地址
     * @param fromEmailName      發件人郵箱顯示名稱
     * @param subject            主題
     * @param content            郵件正文
     * @param toEmailAddressList 收件人郵箱集合(支援群發)
     * @return true:成功;false:失敗
     */
    @Override
    public boolean sendImageHtmlEmail(String fromEmailAddress, String fromEmailName, String subject, String content, List<String> toEmailAddressList, ImageMailDto[] imageData) throws RuntimeException {
        if (CollectionUtils.isEmpty(toEmailAddressList)) {
            throw new RuntimeException("toEmailAddressList is empty!");
        }
        if (toEmailAddressList.size() > MAX_SEND_SIZE) {
            throw new RuntimeException("toEmailAddressList is more than [" + MAX_SEND_SIZE + "]!");
        }

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", hostName);
            props.put("mail.smtp.auth", "true");

            Session sendMailSession = Session.getDefaultInstance(props, authenticator);
            MimeMessage mimeMessage = new MimeMessage(sendMailSession);
            mimeMessage.setFrom(new InternetAddress(fromEmailAddress));
            InternetAddress[] address = new InternetAddress().parse(toEmailAddressList.toString());
            mimeMessage.setRecipients(Message.RecipientType.TO, address);
            mimeMessage.setSubject(subject);
            mimeMessage.setSentDate(new Date());
            BodyPart mdp = new MimeBodyPart();//新建一個存放信件內容的BodyPart物件
            mdp.setContent(content, "text/html;charset=utf-8");//給BodyPart物件設定內容和格式/編碼方式


            Multipart mm = new MimeMultipart();//新建一個MimeMultipart物件用來存放BodyPart對
            mm.addBodyPart(mdp);//將BodyPart加入到MimeMultipart物件中(可以加入多個BodyPart)

            if (imageData != null) {
                for (ImageMailDto dto : imageData) {
                    MimeBodyPart image = new MimeBodyPart();
                    image.setDataHandler(new DataHandler(new ByteArrayDataSource(dto.getImageData(), dto.getMimeType())));  //javamail jaf
                    image.setContentID(dto.getImageCid());
                    mm.addBodyPart(image);
                }
            }

            mimeMessage.setContent(mm);//把mm作為訊息物件的內容
            mimeMessage.saveChanges();

            Transport.send(mimeMessage);
            return true;
        } catch (Exception e) {
            log.error("郵件傳送異常郵件地址" + toEmailAddressList, e);
            throw new RuntimeException(e);
        }

    }

鑑權類寫法:

  Authenticator authenticator = new DefaultAuthenticator(props.getProperty("mail.smtp.user"),props.getProperty("mail.smtp.password"));


圖片儲存類(自定義,可以修改替換):
import java.io.Serializable;

/**
 * 郵件傳送圖片
 *
 * @author wangqing
 * @since 16-3-2 下午4:39
 */
public class ImageMailDto implements Serializable {

    private static final long serialVersionUID = 1L;

    private byte[] imageData;
    private String imageCid;//"好好工作<img src=\"cid:abcd\">"
    private String mimeType;//like image/jpeg、image/bmp、image/gif


    public byte[] getImageData() {
        return imageData;
    }

    public void setImageData(byte[] imageData) {
        this.imageData = imageData;
    }

    public String getImageCid() {
        return imageCid;
    }

    public void setImageCid(String imageCid) {
        this.imageCid = imageCid;
    }

    public String getMimeType() {
        return mimeType;
    }

    public void setMimeType(String mimeType) {
        this.mimeType = mimeType;
    }

}