Java Code Examples for javax.mail.internet.MimeMultipart#setSubType()

The following examples show how to use javax.mail.internet.MimeMultipart#setSubType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Mail4Customize.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean send(Message msg) {
    boolean isOk = true;
    Transport transport = null;
    try {
        LOG.info(String.format("Address: %s", msg.getAddress()));
        LOG.info(String.format("Subject: %s", msg.getSubject() + ENV));
        LOG.info(String.format("Contents: %s", msg.getContents()));
        LOG.info(String.format("Host: %s", msg.getHost()));
        LOG.info(String.format("Port: %s", msg.getPort()));
        LOG.info(String.format("User name: %s", msg.getUserName()));

        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", msg.getHost());

        Session session = Session.getInstance(props);
        // session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(msg.getFromAddress());
        message.setRecipients(javax.mail.Message.RecipientType.TO, msg.getAddress());
        message.setSubject(msg.getSubject());

        MimeMultipart mmp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent(msg.getContents(), "text/html;charset=UTF-8");

        mmp.addBodyPart(mbp);
        mmp.setSubType("mixed");

        message.setContent(mmp);
        message.setSentDate(new Date());

        transport = session.getTransport();
        transport.connect(msg.getHost(), msg.getPort(), msg.getUserName(), msg.getPassword());
        transport.sendMessage(message, message.getAllRecipients());

        LOG.error("mail for customize send email success.");
    } catch (Exception e) {
        isOk = false;
        LOG.error("mail for customize send email fail.", e);
    } finally {
        close(transport);
    }
    return isOk;
}
 
Example 2
Source File: EmailFormatterOutboud.java    From matrix-appservice-email with GNU Affero General Public License v3.0 4 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, List<_BridgeMessageContent> contents, boolean allowReply) throws MessagingException, IOException {
    MimeMultipart body = new MimeMultipart();
    body.setSubType("alternative");

    for (_BridgeMessageContent content : contents) {
        MimeMultipart contentBody = new MimeMultipart();
        contentBody.setSubType("related");

        Optional<_EmailTemplateContent> contentTemplateOpt = template.getContent(content.getMime());
        if (!contentTemplateOpt.isPresent()) {
            continue;
        }

        _EmailTemplateContent contentTemplate = contentTemplateOpt.get();
        contentBody.addBodyPart(makeBodyPart(data, contentTemplate, content));

        if (contentTemplate.getContent().contains(EmailTemplateToken.SenderAvatar.getToken()) &&
                data.getSenderAvatar() != null && data.getSenderAvatar().isValid()) {
            log.info("Adding avatar for sender");

            MimeBodyPart avatarBp = new MimeBodyPart();
            _MatrixContent avatar = data.getSenderAvatar();
            String filename = avatar.getFilename()
                    .map(f -> f.replace("image/", "").replace("\"", ""))
                    .filter(StringUtils::isNotBlank)
                    .orElseGet(() -> "unknown." + avatar.getType());

            avatarBp.setContent(avatar.getData(), avatar.getType());
            avatarBp.setContentID("<" + senderAvatarId + ">");
            avatarBp.setDisposition("inline; filename=\"" + filename + "\"; size=" + avatar.getData().length + ";");

            contentBody.addBodyPart(avatarBp);
        }

        MimeBodyPart part = new MimeBodyPart();
        part.setContent(contentBody);

        body.addBodyPart(part);
    }

    return makeEmail(data, template, body, allowReply);
}
 
Example 3
Source File: SendAttachmentMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    prop.setProperty("mail.debug", "true");
    prop.setProperty("mail.host", MAIL_SERVER_HOST);
    prop.setProperty("mail.transport.protocol", "smtp");
    prop.setProperty("mail.smtp.auth", "true");

    // 1、创建session
    Session session = Session.getInstance(prop);

    // 2、通过session得到transport对象
    Transport ts = session.getTransport();

    // 3、连上邮件服务器
    ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

    // 4、创建邮件
    MimeMessage message = new MimeMessage(session);

    // 邮件消息头
    message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
    message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
    message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
    message.setSubject("测试带附件邮件"); // 邮件的标题

    MimeBodyPart text = new MimeBodyPart();
    text.setContent("邮件中有两个附件。", "text/html;charset=UTF-8");

    // 描述数据关系
    MimeMultipart mm = new MimeMultipart();
    mm.setSubType("related");
    mm.addBodyPart(text);
    String[] files = { "D:\\00_Temp\\temp\\1.jpg", "D:\\00_Temp\\temp\\2.png" };

    // 添加邮件附件
    for (String filename : files) {
        MimeBodyPart attachPart = new MimeBodyPart();
        attachPart.attachFile(filename);
        mm.addBodyPart(attachPart);
    }

    message.setContent(mm);
    message.saveChanges();

    // 5、发送邮件
    ts.sendMessage(message, message.getAllRecipients());
    ts.close();
}
 
Example 4
Source File: sendHtmlMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	Properties prop = new Properties();
	prop.setProperty("mail.debug", "true");
	prop.setProperty("mail.host", MAIL_SERVER_HOST);
	prop.setProperty("mail.transport.protocol", "smtp");
	prop.setProperty("mail.smtp.auth", "true");

	// 1、创建session
	Session session = Session.getInstance(prop);
	Transport ts = null;

	// 2、通过session得到transport对象
	ts = session.getTransport();

	// 3、连上邮件服务器
	ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

	// 4、创建邮件
	MimeMessage message = new MimeMessage(session);

	// 邮件消息头
	message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
	message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
	message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
	message.setSubject("测试HTML邮件"); // 邮件的标题

	String htmlContent = "<h1>Hello</h1>" + "<p>显示图片<img src='cid:abc.jpg'>1.jpg</p>";
	MimeBodyPart text = new MimeBodyPart();
	text.setContent(htmlContent, "text/html;charset=UTF-8");
	MimeBodyPart image = new MimeBodyPart();
	DataHandler dh = new DataHandler(new FileDataSource("D:\\05_Datas\\图库\\吉他少年背影.png"));
	image.setDataHandler(dh);
	image.setContentID("abc.jpg");

	// 描述数据关系
	MimeMultipart mm = new MimeMultipart();
	mm.addBodyPart(text);
	mm.addBodyPart(image);
	mm.setSubType("related");
	message.setContent(mm);
	message.saveChanges();

	// 5、发送邮件
	ts.sendMessage(message, message.getAllRecipients());
	ts.close();
}
 
Example 5
Source File: AS2ReceiverHandler.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void createMDNData(Session session, MessageMDN mdn, String micAlg, String signatureProtocol) throws Exception {
    // Create the report and sub-body parts
    MimeMultipart reportParts = new MimeMultipart();

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    String text = mdn.getText() + "\r\n";
    textPart.setContent(text, "text/plain");
    textPart.setHeader("Content-Type", "text/plain");
    reportParts.addBodyPart(textPart);

    // Create the report part
    MimeBodyPart reportPart = new MimeBodyPart();
    InternetHeaders reportValues = new InternetHeaders();
    reportValues.setHeader("Reporting-UA", mdn.getAttribute(AS2MessageMDN.MDNA_REPORTING_UA));
    reportValues.setHeader("Original-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_RECIPIENT));
    reportValues.setHeader("Final-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_FINAL_RECIPIENT));
    reportValues.setHeader("Original-Message-ID", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
    reportValues.setHeader("Disposition", mdn.getAttribute(AS2MessageMDN.MDNA_DISPOSITION));
    reportValues.setHeader("Received-Content-MIC", mdn.getAttribute(AS2MessageMDN.MDNA_MIC));

    Enumeration<String> reportEn = reportValues.getAllHeaderLines();
    StringBuffer reportData = new StringBuffer();

    while (reportEn.hasMoreElements()) {
        reportData.append(reportEn.nextElement()).append("\r\n");
    }

    reportData.append("\r\n");

    String reportText = reportData.toString();
    reportPart.setContent(reportText, AS2Standards.DISPOSITION_TYPE);
    reportPart.setHeader("Content-Type", AS2Standards.DISPOSITION_TYPE);
    reportParts.addBodyPart(reportPart);

    // Convert report parts to MimeBodyPart
    MimeBodyPart report = new MimeBodyPart();
    reportParts.setSubType(AS2Standards.REPORT_SUBTYPE);
    report.setContent(reportParts);
    String contentType = reportParts.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_multipart_content_type_header_folding", "false"))) {
        contentType = contentType.replaceAll("\r\n[ \t]*", " ");
    }
    report.setHeader("Content-Type", contentType);

    // Sign the data if needed
    if (signatureProtocol != null) {
        CertificateFactory certFx = session.getCertificateFactory();

        try {
            // The receiver of the original message is the sender of the MDN....
            X509Certificate senderCert = certFx.getCertificate(mdn, Partnership.PTYPE_RECEIVER);
            PrivateKey senderKey = certFx.getPrivateKey(mdn, senderCert);
            Partnership p = mdn.getPartnership();
            String contentTxfrEncoding = p.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
            boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(p.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
            if (contentTxfrEncoding == null) {
                contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
            }
            // sign the data using CryptoHelper
            MimeBodyPart signedReport = AS2Util.getCryptoHelper().sign(report, senderCert, senderKey, micAlg, contentTxfrEncoding, false, isRemoveCmsAlgorithmProtectionAttr);
            mdn.setData(signedReport);
        } catch (CertificateNotFoundException cnfe) {
            cnfe.terminate();
            mdn.setData(report);
        } catch (KeyNotFoundException knfe) {
            knfe.terminate();
            mdn.setData(report);
        }
    } else {
        mdn.setData(report);
    }

    // Update the MDN headers with content information
    MimeBodyPart data = mdn.getData();
    String headerContentType = data.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_http_header_folding", "true"))) {
        headerContentType = headerContentType.replaceAll("\r\n[ \t]*", " ");
    }
    mdn.setHeader("Content-Type", headerContentType);

    // int size = getSize(data);
    // mdn.setHeader("Content-Length", Integer.toString(size));
}