javax.mail.util.ByteArrayDataSource Java Examples

The following examples show how to use javax.mail.util.ByteArrayDataSource. 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: SpringJavaEmailSender.java    From DataSphereStudio with Apache License 2.0 7 votes vote down vote up
private MimeMessage parseToMimeMessage(Email email) {
    MimeMessage message = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        if(StringUtils.isBlank(email.getFrom())) {
            messageHelper.setFrom(SendEmailAppJointConfiguration.DEFAULT_EMAIL_FROM().getValue());
        } else {
            messageHelper.setFrom(email.getFrom());
        }
        messageHelper.setSubject(email.getSubject());
        messageHelper.setTo(email.getTo());
        messageHelper.setCc(email.getCc());
        messageHelper.setBcc(email.getBcc());
        for(Attachment attachment: email.getAttachments()){
            messageHelper.addAttachment(attachment.getName(), new ByteArrayDataSource(attachment.getBase64Str(), attachment.getMediaType()));
        }
        messageHelper.setText(email.getContent(), true);
    } catch (Exception e) {
        logger.error("Send mail failed", e);
    }
    return message;
}
 
Example #2
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example #3
Source File: MailHandler.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Set the content for a part using the encoding assigned to the handler.
 * @param part the part to assign.
 * @param buf the formatted data.
 * @param type the mime type or null, meaning text/plain.
 * @throws MessagingException if there is a problem.
 */
private void setContent(MimePart part, CharSequence buf, String type) throws MessagingException {
    final String charset = getEncodingName();
    if (type != null && !"text/plain".equalsIgnoreCase(type)) {
        type = contentWithEncoding(type, charset);
        try {
            DataSource source = new ByteArrayDataSource(buf.toString(), type);
            part.setDataHandler(new DataHandler(source));
        } catch (final IOException IOE) {
            reportError(IOE.getMessage(), IOE, ErrorManager.FORMAT_FAILURE);
            part.setText(buf.toString(), charset);
        }
    } else {
        part.setText(buf.toString(), MimeUtility.mimeCharset(charset));
    }
}
 
Example #4
Source File: NotificationSender.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
public void sendEmail( String msgBody, String subject ) {
	Properties prop = new Properties( System.getProperties() );
	prop.put( "mail.smtp.host", emailHost );

	Session session = Session.getDefaultInstance( prop, null );

	try {

		Message msg = new MimeMessage( session );
		msg.setFrom( new InternetAddress( "[email protected]", ags ) );

		msg.addRecipient( Message.RecipientType.TO, new InternetAddress( mailingList ) );

		msg.setSubject( getUpdatedSubject( subject ) );

		msg.setDataHandler( new DataHandler( new ByteArrayDataSource( msgBody, "text/plain" ) ) );
		javax.mail.Transport.send( msg );
	} catch ( Exception ex ) {
		log.error( ex.getMessage() );
	}
}
 
Example #5
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void echoData(Holder<String> text, Holder<DataHandler> data) {

        try {
            InputStream bis = null;
            bis = data.value.getDataSource().getInputStream();
            byte[] b = new byte[6];
            bis.read(b, 0, 6);
            String string = IOUtils.newStringFromBytes(b);

            ByteArrayDataSource source =
                new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
            data.value = new DataHandler(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example #6
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void echoDataWithHeader(Holder<String> text,
                               Holder<DataHandler> data,
                               Holder<String> headerText) {
    try {
        InputStream bis = null;
        bis = data.value.getDataSource().getInputStream();
        byte[] b = new byte[6];
        bis.read(b, 0, 6);
        String string = IOUtils.newStringFromBytes(b);

        ByteArrayDataSource source =
            new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
        data.value = new DataHandler(source);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #7
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwa() throws Exception {
    SwAService service = new SwAService();

    SwAServiceInterface port = service.getSwAServiceHttpPort();
    setAddress(port, "http://localhost:" + serverPort + "/swa");

    Holder<String> textHolder = new Holder<>();
    Holder<DataHandler> data = new Holder<>();

    ByteArrayDataSource source = new ByteArrayDataSource("foobar".getBytes(), "application/octet-stream");
    DataHandler handler = new DataHandler(source);

    data.value = handler;

    textHolder.value = "Hi";

    port.echoData(textHolder, data);
    InputStream bis = null;
    bis = data.value.getDataSource().getInputStream();
    byte[] b = new byte[10];
    bis.read(b, 0, 10);
    String string = IOUtils.newStringFromBytes(b);
    assertEquals("testfoobar", string);
    assertEquals("Hi", textHolder.value);
}
 
Example #8
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSwaDataStruct() throws Exception {
    SwAService service = new SwAService();

    SwAServiceInterface port = service.getSwAServiceHttpPort();
    setAddress(port, "http://localhost:" + serverPort + "/swa");

    Holder<DataStruct> structHolder = new Holder<>();

    ByteArrayDataSource source = new ByteArrayDataSource("foobar".getBytes(), "application/octet-stream");
    DataHandler handler = new DataHandler(source);

    DataStruct struct = new DataStruct();
    struct.setDataRef(handler);
    structHolder.value = struct;

    port.echoDataRef(structHolder);

    handler = structHolder.value.getDataRef();
    InputStream bis = handler.getDataSource().getInputStream();
    byte[] b = new byte[10];
    bis.read(b, 0, 10);
    String string = IOUtils.newStringFromBytes(b);
    assertEquals("testfoobar", string);
    bis.close();
}
 
Example #9
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void echoData(Holder<String> text, Holder<DataHandler> data) {

        try {
            InputStream bis = null;
            bis = data.value.getDataSource().getInputStream();
            byte[] b = new byte[6];
            bis.read(b, 0, 6);
            String string = IOUtils.newStringFromBytes(b);

            ByteArrayDataSource source =
                new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
            data.value = new DataHandler(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example #10
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void echoDataWithHeader(Holder<String> text,
                               Holder<DataHandler> data,
                               Holder<String> headerText) {
    try {
        InputStream bis = null;
        bis = data.value.getDataSource().getInputStream();
        byte[] b = new byte[6];
        bis.read(b, 0, 6);
        String string = IOUtils.newStringFromBytes(b);

        ByteArrayDataSource source =
            new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
        data.value = new DataHandler(source);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #11
Source File: InvoiceFacade.java    From jpa-invoicer with The Unlicense 6 votes vote down vote up
public void sendInvoice(final Invoice invoice) throws EmailException, IOException {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writeAsPdf(invoice, out);
        ByteArrayDataSource dataSource =
                new ByteArrayDataSource(out.toByteArray(), "application/pdf");
        String fileName = "invoice_" + invoice.getInvoiceNumber() + ".pdf";

        MultiPartEmail email = new MultiPartEmail();
        email.setAuthentication(smtpUsername, smtpPassword);
        email.setHostName(smtpHostname);
        email.setSmtpPort(smtpPort);
        email.setFrom(smtpFrom);
        email.addTo(invoice.getInvoicer().getEmail());
        email.setSubject(smtpSubject);
        email.setMsg(smtpMessage);
        email.attach(dataSource, fileName, "Invoice");
        email.send();
    }
}
 
Example #12
Source File: GMailClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    StringBuilder sb = new StringBuilder();
    for (QrHolder qrHolder : attachmentData) {
        sb.append(qrHolder.token)
        .append(",")
        .append(qrHolder.deviceId)
        .append(",")
        .append(qrHolder.dashId)
        .append("\n");
    }
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    ByteArrayDataSource source = new ByteArrayDataSource(sb.toString(), "text/csv");
    attachmentsPart.setDataHandler(new DataHandler(source));
    attachmentsPart.setFileName("tokens.csv");

    multipart.addBodyPart(attachmentsPart);
}
 
Example #13
Source File: ReadHeaderInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadSOAPEnvelopeNamespace() throws Exception {
    soapMessage = TestUtil.createEmptySoapMessage(Soap12.getInstance(), chain);
    InputStream in = getClass().getResourceAsStream("test-bad-env.xml");
    assertNotNull(in);
    ByteArrayDataSource bads = new ByteArrayDataSource(in, "test/xml");
    soapMessage.setContent(InputStream.class, bads.getInputStream());

    ReadHeadersInterceptor r = new ReadHeadersInterceptor(BusFactory.getDefaultBus());
    try {
        r.handleMessage(soapMessage);
        fail("Did not throw exception");
    } catch (SoapFault f) {
        assertEquals(Soap11.getInstance().getVersionMismatch(), f.getFaultCode());
    }
}
 
Example #14
Source File: ReadHeaderInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadSOAPEnvelopeName() throws Exception {
    soapMessage = TestUtil.createEmptySoapMessage(Soap12.getInstance(), chain);
    InputStream in = getClass().getResourceAsStream("test-bad-envname.xml");
    assertNotNull(in);
    ByteArrayDataSource bads = new ByteArrayDataSource(in, "test/xml");
    soapMessage.setContent(InputStream.class, bads.getInputStream());

    ReadHeadersInterceptor r = new ReadHeadersInterceptor(BusFactory.getDefaultBus());
    try {
        r.handleMessage(soapMessage);
        fail("Did not throw exception");
    } catch (SoapFault f) {
        assertEquals(Soap11.getInstance().getSender(), f.getFaultCode());
    }
}
 
Example #15
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void echoDataRef(Holder<DataStruct> data) {
    try {
        InputStream bis = null;
        bis = data.value.getDataRef().getDataSource().getInputStream();
        byte[] b = new byte[6];
        bis.read(b, 0, 6);
        String string = IOUtils.newStringFromBytes(b);

        ByteArrayDataSource source =
            new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
        data.value.setDataRef(new DataHandler(source));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: MultipartStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/xop")
@Consumes("multipart/related")
@Produces("multipart/related;type=text/xml")
@Multipart("xop")
public XopType addBookXop(@Multipart XopType type) throws Exception {
    if (!"xopName".equals(type.getName())) {
        throw new RuntimeException("Wrong name property");
    }
    String bookXsd = IOUtils.readStringFromStream(type.getAttachinfo().getInputStream());
    String bookXsd2 = IOUtils.readStringFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    if (!bookXsd.equals(bookXsd2)) {
        throw new RuntimeException("Wrong attachinfo property");
    }
    String bookXsdRef = IOUtils.readStringFromStream(type.getAttachInfoRef().getInputStream());
    if (!bookXsdRef.equals(bookXsd2)) {
        throw new RuntimeException("Wrong attachinforef property");
    }
    if (!Boolean.getBoolean("java.awt.headless") && type.getImage() == null) {
        throw new RuntimeException("Wrong image property");
    }
    context.put(org.apache.cxf.message.Message.MTOM_ENABLED,
                "true");

    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachinfo2(bookXsd.getBytes());

    xop.setImage(ImageIO.read(getClass().getResource(
            "/org/apache/cxf/systest/jaxrs/resources/java.jpg")));
    return xop;
}
 
Example #17
Source File: MimeMessageBuilder.java    From james-project with Apache License 2.0 5 votes vote down vote up
public BodyPart build() throws IOException, MessagingException {
    Preconditions.checkState(!(dataAsString.isPresent() && dataAsBytes.isPresent()), "Can not specify data as bytes and data as string at the same time");
    MimeBodyPart bodyPart = new MimeBodyPart();
    if (dataAsBytes.isPresent()) {
        bodyPart.setDataHandler(
            new DataHandler(
                new ByteArrayDataSource(
                    dataAsBytes.get(),
                    type.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE))
            ));
    } else {
        bodyPart.setDataHandler(
            new DataHandler(
                new ByteArrayDataSource(
                    dataAsString.orElse(DEFAULT_VALUE),
                    type.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE))
            ));
    }
    if (filename.isPresent()) {
        bodyPart.setFileName(filename.get());
    }
    if (cid.isPresent()) {
        bodyPart.setContentID(cid.get());
    }
    if (disposition.isPresent()) {
        bodyPart.setDisposition(disposition.get());
    }
    List<Header> headerList = headers.build();
    for (Header header: headerList) {
        bodyPart.addHeader(header.name, header.value);
    }
    return bodyPart;
}
 
Example #18
Source File: AttachmentTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Attachment createAttachment(String id) {
    MetadataMap<String, String> map = new MetadataMap<>();
    map.add("foo", "bar");
    return new Attachment(id,
                   new DataHandler(new ByteArrayDataSource(new byte[]{1}, "application/octet-stream")),
                   map);
}
 
Example #19
Source File: AttachmentMailerImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Construct and a send mime email message from an Attachment Mail Message.
 *
 * @param message the Attachement Mail Message
 * @throws MessagingException
 */
@Override
public void sendEmail(AttachmentMailMessage message) throws MessagingException {
    // Construct a mime message from the Attachment Mail Message

    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(message.getMessage());

    MimeBodyPart attachment = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);
    ByteArrayDataSource ds = new ByteArrayDataSource(message.getContent(), message.getType());
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName(message.getFileName());
    multipart.addBodyPart(attachment);
    mimeMessage.setContent(multipart);

    MimeMailMessage mmm = new MimeMailMessage(mimeMessage);

    mmm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
    mmm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
    mmm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
    mmm.setSubject(message.getSubject());
    mmm.setFrom(message.getFromAddress());

    try {
        if ( LOG.isDebugEnabled() ) {
            LOG.debug( "sendEmail() - Sending message: " + mmm.toString() );
        }
        mailSender.send(mmm.getMimeMessage());
    }
    catch (Exception e) {
        LOG.error("sendEmail() - Error sending email.", e);
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: EmailSenderService.java    From batchers with Apache License 2.0 5 votes vote down vote up
private void attachEmailAttachmentTOs(HtmlEmail email, List<EmailAttachmentTO> attachments) throws EmailException {
    for (EmailAttachmentTO attachmentTO : attachments) {
        email.attach(new ByteArrayDataSource(attachmentTO.getBytes(), attachmentTO.getMimeType()),
                attachmentTO.getName(), attachmentTO.getDescription(),
                EmailAttachment.ATTACHMENT);
    }
}
 
Example #21
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwa() throws Exception {
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setWsdlLocation("classpath:/swa-mime_jms.wsdl");
    factory.setTransportId(SoapJMSConstants.SOAP_JMS_SPECIFICIATION_TRANSPORTID);
    factory.setServiceName(new QName("http://cxf.apache.org/swa", "SwAService"));
    factory.setEndpointName(new QName("http://cxf.apache.org/swa", "SwAServiceJMSPort"));
    factory.setAddress(ADDRESS + broker.getEncodedBrokerURL());
    factory.getOutInterceptors().add(new LoggingOutInterceptor());
    SwAService port = factory.create(SwAService.class);


    Holder<String> textHolder = new Holder<>();
    Holder<DataHandler> data = new Holder<>();

    ByteArrayDataSource source = new ByteArrayDataSource("foobar".getBytes(), "application/octet-stream");
    DataHandler handler = new DataHandler(source);

    data.value = handler;

    textHolder.value = "Hi";

    port.echoData(textHolder, data);
    InputStream bis = null;
    bis = data.value.getDataSource().getInputStream();
    byte[] b = new byte[10];
    bis.read(b, 0, 10);
    String string = IOUtils.newStringFromBytes(b);
    assertEquals("testfoobar", string);
    assertEquals("Hi", textHolder.value);

    if (port instanceof Closeable) {
        ((Closeable)port).close();
    }
}
 
Example #22
Source File: DataSourceProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static MimeMultipart readAttachmentParts(String contentType, InputStream bais) throws
    MessagingException, IOException {
    DataSource source = new ByteArrayDataSource(bais, contentType);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage mm = new MimeMessage(session);
    mm.setContent(mpart);
    mm.addHeaderLine("Content-Type:" + contentType);
    return (MimeMultipart) mm.getContent();
}
 
Example #23
Source File: MailItemTest.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void getAttachments() throws Exception {
    List<DataSource> sources = new LinkedList<DataSource>();
    sources.add(new ByteArrayDataSource("attachment1", "text"));
    sources.add(new ByteArrayDataSource("attachment2", "text"));

    item.setAttachments(sources);
    assertEquals(sources, item.getAttachments());
}
 
Example #24
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void echoDataRef(Holder<DataStruct> data) {
    try {
        InputStream bis = null;
        bis = data.value.getDataRef().getDataSource().getInputStream();
        byte[] b = new byte[6];
        bis.read(b, 0, 6);
        String string = IOUtils.newStringFromBytes(b);

        ByteArrayDataSource source =
            new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
        data.value.setDataRef(new DataHandler(source));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: MimeMessageBodyGenerator.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Multipart addTextPart(Multipart multipart, String text, String contentType) throws MessagingException, IOException {
    MimeBodyPart textReasonPart = new MimeBodyPart();
    textReasonPart.setDataHandler(
        new DataHandler(
            new ByteArrayDataSource(
                text,
                contentType + "; charset=UTF-8")));
    multipart.addBodyPart(textReasonPart);
    return multipart;
}
 
Example #26
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldDetectBigMDN() throws Exception {

    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
        new DataHandler(
            new ByteArrayDataSource(
                Joiner.on("\r\n").join(
                    "Final-Recipient: rfc822;[email protected]",
                    "Disposition: automatic-action/MDN-sent-automatically; displayed",
                    ""),
                "message/disposition-notification;")
        ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    BodyPart bigBody = MimeMessageBuilder.bodyPartBuilder() // ~3MB
        .data("12345678\r\n".repeat(300 * 1024))
        .build();
    multipart.addBodyPart(bigBody);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
        .name("mail")
        .sender(MailAddressFixture.ANY_AT_JAMES)
        .mimeMessage(message)
        .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example #27
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldNotFilterManuallySentMdn() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                        Joiner.on("\r\n").join(
                            "Final-Recipient: rfc822;[email protected]",
                            "Disposition: manual-action/MDN-sent-manually; displayed",
                            ""),
                            "message/disposition-notification; charset=UTF-8")
                    ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example #28
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldBeDetected() throws Exception {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                        Joiner.on("\r\n").join(
                            "Final-Recipient: rfc822;[email protected]",
                            "Disposition: automatic-action/MDN-sent-automatically; displayed",
                            ""),
                            "message/disposition-notification;")
                    ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example #29
Source File: SmartSendMailUtil.java    From smart-admin with MIT License 5 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param sendMail 发件人邮箱
 * @param sendMailPwd 发件人密码
 * @param sendMailName 发件人昵称(可选)
 * @param receiveMail 收件人邮箱
 * @param receiveMailName 收件人昵称(可选)
 * @param sendSMTPHost 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
 * @param title 邮件主题
 * @param content 邮件正文
 * @author Administrator
 * @date 2017年12月13日 下午1:51:38
 */
public static void sendFileMail(String sendMail, String sendMailPwd, String sendMailName, String[] receiveMail, String receiveMailName, String sendSMTPHost, String title, String content,
                                InputStream is, String fileName, String port) {

    Session session = createSSLSession(sendSMTPHost, port, sendMailName, sendMailPwd);
    // 3. 创建一封邮件
    MimeMessage message;
    try {
        message = createMimeMessage(session, sendMail, sendMailName, receiveMail, receiveMailName, title, content);
        // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
        MimeMultipart mm = new MimeMultipart();
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");
        mm.addBodyPart(text);
        if (null != is && is.available() > 0) {
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(is, "application/msexcel");
            // 将附件数据添加到"节点"
            attachment.setDataHandler(new DataHandler(source));
            // 设置附件的文件名(需要编码)
            attachment.setFileName(MimeUtility.encodeText(fileName));
            // 10. 设置文本和 附件 的关系(合成一个大的混合"节点" / Multipart )
            // 如果有多个附件,可以创建多个多次添加
            mm.addBodyPart(attachment);
        }
        message.setContent(mm);
        message.saveChanges();
        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport("smtp");
        transport.connect(sendSMTPHost, sendMail, sendMailPwd);
        //            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        // 7. 关闭连接
    } catch (Exception e) {
        log.error("", e);
    }

}
 
Example #30
Source File: ThirdPartyMailClient.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendHtmlWithAttachment(String to, String subj, String body, QrHolder[] attachments) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");

    Multipart multipart = new MimeMultipart();

    MimeBodyPart bodyMessagePart = new MimeBodyPart();
    bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);
    multipart.addBodyPart(bodyMessagePart);

    for (QrHolder qrHolder : attachments) {
        MimeBodyPart attachmentsPart = new MimeBodyPart();
        attachmentsPart.setDataHandler(new DataHandler(new ByteArrayDataSource(qrHolder.data, "image/jpeg")));
        attachmentsPart.setFileName(qrHolder.makeQRFilename());
        multipart.addBodyPart(attachmentsPart);
    }

    message.setContent(multipart);

    try (Transport transport = session.getTransport()) {
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
    }

    log.debug("Mail sent to {}. Subj: {}", to, subj);
    log.trace("Mail body: {}", body);
}