/** * This method builds {@link Multipart} based on {@link ContentModel} * * @param fileInfo - Source file information {@link FileInfo} * @throws MessagingException */ private Multipart buildContentModelMultipart() throws MessagingException { MimeMultipart rootMultipart = new AlfrescoMimeMultipart("alternative", this.messageFileInfo); // Cite MOB-395: "email agent will be used to select an appropriate template" - we are not able // to // detect an email agent so we use a default template for all messages. // See AlfrescoImapConst to see the possible templates to use. if (isMessageInSitesLibrary) { String bodyTxt = getEmailBodyText(EmailBodyFormat.SHARE_TEXT_PLAIN); rootMultipart.addBodyPart( getTextBodyPart( bodyTxt, EmailBodyFormat.SHARE_TEXT_PLAIN.getSubtype(), EmailBodyFormat.SHARE_TEXT_PLAIN.getMimeType())); String bodyHtml = getEmailBodyText(EmailBodyFormat.SHARE_TEXT_HTML); rootMultipart.addBodyPart( getTextBodyPart( bodyHtml, EmailBodyFormat.SHARE_TEXT_HTML.getSubtype(), EmailBodyFormat.SHARE_TEXT_HTML.getMimeType())); } else { String bodyTxt = getEmailBodyText(EmailBodyFormat.ALFRESCO_TEXT_PLAIN); rootMultipart.addBodyPart( getTextBodyPart( bodyTxt, EmailBodyFormat.ALFRESCO_TEXT_PLAIN.getSubtype(), EmailBodyFormat.ALFRESCO_TEXT_PLAIN.getMimeType())); String bodyHtml = getEmailBodyText(EmailBodyFormat.ALFRESCO_TEXT_HTML); rootMultipart.addBodyPart( getTextBodyPart( bodyHtml, EmailBodyFormat.ALFRESCO_TEXT_HTML.getSubtype(), EmailBodyFormat.ALFRESCO_TEXT_HTML.getMimeType())); } return rootMultipart; }
@Test public void html() throws Exception { String subject = "html"; buildSMTPAppender(subject, SYNCHRONOUS); smtpAppender.setAsynchronousSending(false); smtpAppender.setLayout(buildHTMLLayout()); smtpAppender.start(); logger.addAppender(smtpAppender); logger.debug("html"); logger.error("en error", new Exception("an exception")); MimeMultipart mp = verifyAndExtractMimeMultipart(subject); // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd SAXReader reader = new SAXReader(); reader.setValidation(true); reader.setEntityResolver(new XHTMLEntityResolver()); byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream()); ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes); try { reader.read(bais); } catch (DocumentException de) { System.out.println("incoming message:"); System.out.println(new String(messageBytes)); throw de; } }
public void setMessageContent( MimeMessage message, String subject, String bodyText, String bodyHtml) { try { message.setSubject(subject); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(bodyText.toString(), "UTF-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(bodyHtml.toString(), "text/html; charset=UTF-8"); MimeMultipart multiPart = new MimeMultipart(); // "alternative" means display only one or the other, "mixed" means both multiPart.setSubType("alternative"); // I read something on the internet saying to put the text part first // so sucktastic mail clients see it first multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); } catch (MessagingException e) { throw new RuntimeException("failed to put together MIME message", e); } }
// http://jira.qos.ch/browse/LBCLASSIC-221 @Test public void bufferShouldBeResetBetweenMessages() throws Exception { buildSMTPAppender(smtpServer.getSmtp().getPort(), SYNCHRONOUS); smtpAppender.setLayout(buildPatternLayout(lc, DEFAULT_PATTERN)); smtpAppender.start(); logger.addAppender(smtpAppender); String msg0 = "hello zero"; logger.debug(msg0); logger.error("error zero"); String msg1 = "hello one"; logger.debug(msg1); logger.error("error one"); waitUntilEmailIsSent(); waitUntilEmailIsReceived(smtpServer, 2); MimeMessage[] mma = smtpServer.getReceivedMessages(); assertNotNull(mma); assertEquals(2, mma.length); MimeMessage mm0 = mma[0]; MimeMultipart content0 = (MimeMultipart) mm0.getContent(); String body0 = GreenMailUtil.getBody(content0.getBodyPart(0)); assertTrue(body0.contains(msg0)); MimeMessage mm1 = mma[1]; MimeMultipart content1 = (MimeMultipart) mm1.getContent(); String body1 = GreenMailUtil.getBody(content1.getBodyPart(0)); // second body should not contain content from first message assertFalse(body1.contains(msg0)); }
private void writeMultipartToNode(Session session, Node message, MimeMultipart multipart) throws RepositoryException, MessagingException, IOException { int count = multipart.getCount(); for (int i = 0; i < count; i++) { createChildNodeForPart(session, i, multipart.getBodyPart(i), message); } }
/** 根据传入的 Seesion 对象创建混合型的 MIME消息 */ public MimeMessage createMessage(Session session) throws Exception { String from = "*****@*****.**"; String to = "*****@*****.**"; String subject = "创建内含附件、图文并茂的邮件!"; String body = "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>" + "<a href = http://haolloyin.blog.51cto.com/> 蚂蚁</a></br>" + "<img src = \"cid:logo_jpg\"></a>"; MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); // 创建邮件的各个 MimeBodyPart 部分 MimeBodyPart attachment01 = createAttachment("F:\\java\\Snake.java"); MimeBodyPart attachment02 = createAttachment("F:\\java\\meng.mp3"); MimeBodyPart content = createContent(body, "F:\\java\\logo.jpg"); // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象 MimeMultipart allPart = new MimeMultipart("mixed"); allPart.addBodyPart(attachment01); allPart.addBodyPart(attachment02); allPart.addBodyPart(content); // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存 msg.setContent(allPart); msg.saveChanges(); return msg; }
/** * Generate a MimeMessage with the specified attributes * * @param destEmailAddr The destination email address * @param fromEmailAddr The sender email address * @param fromName The senders display name * @param emailSubject The subject * @param emailPlainText The message body (plaintext) * @return The MimeMessage object * @throws Exception */ public static MimeMessage generateMail( String destEmailAddr, String destPersonalName, String fromEmailAddr, String fromName, String emailSubject, String emailPlainText) throws Exception { MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false); if (destPersonalName != null) { toAddrs[0].setPersonal(destPersonalName); } InternetAddress from = new InternetAddress(fromEmailAddr); from.setPersonal(fromName); message.setRecipients(Message.RecipientType.TO, toAddrs); message.setFrom(from); message.setSubject(emailSubject); message.setSentDate(new java.util.Date()); MimeMultipart msgbody = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain"))); msgbody.addBodyPart(html); message.setContent(msgbody); return message; }
@Test public void savedWithoutError() throws Exception { Session session = Session.getDefaultInstance(new Properties()); // Instantiate a Multipart object MimeMultipart mp = new MimeMultipart(); // create the first bodypart object MimeBodyPart b1 = new MimeBodyPart(); // create textual content // and add it to the bodypart object b1.setContent("Spaceport Map", "text/plain"); mp.addBodyPart(b1); // Multipart messages usually have more than // one body part. Create a second body part // object, add new text to it, and place it // into the multipart message as well. This // second object holds postscript data. MimeBodyPart b2 = new MimeBodyPart(); b2.setDataHandler(new DataHandler(new FileDataSource("project.xml"))); mp.addBodyPart(b2); // Create a new message object as described above, // and set its attributes. Add the multipart // object to this message and call saveChanges() // to write other message headers automatically. Message msg = new MimeMessage(session); // Set message attrubutes as in a singlepart // message. msg.setContent(mp); // add Multipart msg.saveChanges(); // save changes }
public Multipart generate(Email email) throws MessagingException, IOException, TemplateException { MimeMultipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(bodyPartFactory.createPlainTextBodyPart(email)); multipart.addBodyPart(bodyPartFactory.createHtmlBodyPart(email)); return multipart; }
// http://jira.qos.ch/browse/LBCLASSIC-221 @Test public void bufferShouldBeResetBetweenMessages() throws Exception { buildSMTPAppender("bufferShouldBeResetBetweenMessages", SYNCHRONOUS); smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); smtpAppender.start(); logger.addAppender(smtpAppender); String msg0 = "hello zero"; logger.debug(msg0); logger.error("error zero"); String msg1 = "hello one"; logger.debug(msg1); logger.error("error one"); Thread.yield(); int oldCount = 0; int expectedEmailCount = oldCount + 2; waitForServerToReceiveEmails(expectedEmailCount); MimeMessage[] mma = greenMailServer.getReceivedMessages(); assertNotNull(mma); assertEquals(expectedEmailCount, mma.length); MimeMessage mm0 = mma[oldCount]; MimeMultipart content0 = (MimeMultipart) mm0.getContent(); String body0 = GreenMailUtil.getBody(content0.getBodyPart(0)); MimeMessage mm1 = mma[oldCount + 1]; MimeMultipart content1 = (MimeMultipart) mm1.getContent(); String body1 = GreenMailUtil.getBody(content1.getBodyPart(0)); // second body should not contain content from first message assertFalse(body1.contains(msg0)); }
public boolean sendMail(String subject, String text, File attachmentFile) { try { MailAuthenticator auth = new MailAuthenticator(smtpUser, smtpPass); Properties properties = new Properties(); properties.put("mail.smtp.host", smtpServer); properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, auth); Message msg = new MimeMessage(session); MimeMultipart content = new MimeMultipart("alternative"); MimeBodyPart message = new MimeBodyPart(); message.setText(text); message.setHeader("MIME-Version", "1.0" + "\n"); message.setHeader("Content-Type", message.getContentType()); content.addBodyPart(message); if (attachmentFile != null) { DataSource fileDataSource = new FileDataSource(attachmentFile); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); content.addBodyPart(messageBodyPart); } msg.setContent(content); msg.setSentDate(new Date()); msg.setFrom(new InternetAddress(smtpSender)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpReceiver, false)); msg.setSubject(subject); Transport.send(msg); return true; } catch (Exception e) { // e.getMessage() return false; } }
@Test public void testByteArrayToSMIME() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); TEST_CASE1.writeTo(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ByteArraytoSMIME transformer = new ByteArraytoSMIME(); Object object = transformer.transformMimeMessage(in, null); assertNotNull(object); assertTrue(object instanceof MimeMultipart); MimeMultipart mime = (MimeMultipart) object; assertEquals(TEST_CASE1.getBodyPart(0).getContent(), mime.getBodyPart(0).getContent()); assertEquals(TEST_CASE1.getBodyPart(1).getContent(), mime.getBodyPart(1).getContent()); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } }
@Test public void testSendMessageWithAttachment() throws Exception { final String ATTACHMENT_NAME = "boring-attachment.txt"; // mock smtp server Wiser wiser = new Wiser(); int port = 2525 + (int) (Math.random() * 100); mailSender.setPort(port); wiser.setPort(port); wiser.start(); Date dte = new Date(); String emailSubject = "grepster testSendMessageWithAttachment: " + dte; String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte; ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt"); // a null from should work mailEngine.sendMessage( new String[] {"*****@*****.**"}, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME); mailEngine.sendMessage( new String[] {"*****@*****.**"}, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); // one without and one with from assertTrue(wiser.getMessages().size() == 2); WiserMessage wm = wiser.getMessages().get(0); MimeMessage mm = wm.getMimeMessage(); Object o = wm.getMimeMessage().getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart multi = (MimeMultipart) o; int numOfParts = multi.getCount(); boolean hasTheAttachment = false; for (int i = 0; i < numOfParts; i++) { BodyPart bp = multi.getBodyPart(i); String disp = bp.getDisposition(); if (disp == null) { // the body of the email Object innerContent = bp.getContent(); MimeMultipart innerMulti = (MimeMultipart) innerContent; assertEquals(emailBody, innerMulti.getBodyPart(0).getContent()); } else if (disp.equals(Part.ATTACHMENT)) { // the attachment to the email hasTheAttachment = true; assertEquals(ATTACHMENT_NAME, bp.getFileName()); } else { fail("Did not expect to be able to get here."); } } assertTrue(hasTheAttachment); assertEquals(emailSubject, mm.getSubject()); }
/* * Writes/Sends an Email */ public void writeConfirmationEmail( String firstName, String lastName, String username, String password, String email) { String to = email; String from = "*****@*****.**"; String host = "smtp.ilstu.edu"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.user", "cssumne"); // if needed properties.setProperty("mail.password", "stuC0rb!"); // if needed Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Profile Created!"); String htmlText = "<h1>Congratulations, " + firstName + " " + lastName + "! Your Profile has been created!</h1>" + "<img src=\"cid:image\">" + "<p>Username: "******"</p>" + "<p>Email: " + email + "</p>" + "<p>Password: "******"</p>" + "<p>Thank You for Joining!</p>"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds; fds = new FileDataSource( "C:\\Users\\Corbin\\Desktop\\Github\\WebDevSemesterProject\\SilentAuction\\web\\resources\\bf_logo.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
@Override public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception { if (askGmailPassword || gmailPassword == null || gmailUsername == null) { Pair<String, String> credentials = GuiUtils.askCredentials( ConfigFetch.getSuperParentFrame(), "Enter Gmail Credentials", getGmailUsername(), getGmailPassword()); if (credentials == null) return null; setGmailUsername(credentials.first()); setGmailPassword(credentials.second()); PluginUtils.saveProperties("conf/rockblock.props", this); askGmailPassword = false; } Properties props = new Properties(); props.put("mail.store.protocol", "imaps"); ArrayList<IridiumMessage> messages = new ArrayList<>(); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword()); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); int numMsgs = inbox.getMessageCount(); for (int i = numMsgs; i > 0; i--) { Message m = inbox.getMessage(i); if (m.getReceivedDate().before(timeSince)) { break; } else { MimeMultipart mime = (MimeMultipart) m.getContent(); for (int j = 0; j < mime.getCount(); j++) { BodyPart p = mime.getBodyPart(j); Matcher matcher = pattern.matcher(p.getContentType()); if (matcher.matches()) { InputStream stream = (InputStream) p.getContent(); byte[] data = IOUtils.toByteArray(stream); IridiumMessage msg = process(data, matcher.group(1)); if (msg != null) messages.add(msg); } } } } } catch (NoSuchProviderException ex) { ex.printStackTrace(); System.exit(1); } catch (MessagingException ex) { ex.printStackTrace(); System.exit(2); } return messages; }
public static void collectMultipartContent(MimeMultipart multipart, MBMailMessage collector) throws Exception { for (int i = 0; i < multipart.getCount(); i++) { BodyPart part = multipart.getBodyPart(i); collectPartContent(part, collector); } }
public void send(final Email email) throws MessagingException { if (email.getMessage().getSender().getFromName() == null) { logProblem("error.from.address.cannot.be.null"); abort(); return; } final String from = constructFromString( encode(email.getMessage().getFromName()), email.getMessage().getFromAddress()); final String[] replyTos = email.replyTos(); final Address[] replyToAddresses = new Address[replyTos == null ? 0 : replyTos.length]; if (replyTos != null) { for (int i = 0; i < replyTos.length; i++) { try { replyToAddresses[i] = new InternetAddress(encode(replyTos[i])); } catch (final AddressException e) { logProblem("invalid.reply.to.address: " + replyTos[i]); abort(); return; } } } setFrom(new InternetAddress(from)); setSubject(encode(email.getSubject())); setReplyTo(replyToAddresses); final String body = email.getBody(); final String htmlBody = getHtmlBody(); final MimeMultipart mimeMultipart = createMimeMultipart(body, htmlBody); if (body != null && !body.trim().isEmpty()) { final BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(body); mimeMultipart.addBodyPart(bodyPart); } if (htmlBody != null && !htmlBody.trim().isEmpty()) { final BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(htmlBody, "text/html; charset=utf-8"); mimeMultipart.addBodyPart(bodyPart); } setContent(mimeMultipart); addRecipientsAux(); LOG.info("Sending email {} with message id {}", email.getExternalId(), getMessageID()); Transport.send(this); final Address[] allRecipients = getAllRecipients(); setConfirmedAddresses(allRecipients); }
private static void readMultiPart(MultipartResult res, MimeMultipart multipart) throws MessagingException { for (int i = 0; i < multipart.getCount(); i++) { BodyPart part = multipart.getBodyPart(i); try { if (part.isMimeType("image/*") || part.isMimeType("application/*")) continue; Object content = null; try { content = part.getContent(); } catch (UnsupportedEncodingException ex) { String body = ConvertUtil.inputStreamToString(part.getInputStream()); res.body = body; continue; } if (part.isMimeType("text/plain")) { res.body = content.toString(); } else if (part.isMimeType("text/*")) { res.bodyHtml = content.toString(); } else if (content instanceof MimeMultipart) { readMultiPart(res, (MimeMultipart) content); } else if (content instanceof IMAPNestedMessage) { res.body = getBody((IMAPNestedMessage) content); return; } else if (content instanceof InputStream) { if (content instanceof IMAPInputStream) { String body = ConvertUtil.inputStreamToString(part.getInputStream()); res.body = body; } else System.out.println( String.format( "Ignoring binary content in mail: %s [%s]", part.getContentType(), content.getClass())); } else if (part.isMimeType("message/*")) { res.body = content.toString(); } else { System.out.println( String.format( "Unknown content type in mail: %s [%s]", part.getContentType(), content.getClass())); } } catch (IllegalStateException ex) { System.out.println( String.format("Could not read contents in mail: %s", part.getContentType())); } catch (UnsupportedDataTypeException ex) { System.out.println( String.format("Could not read contents in mail: %s", part.getContentType())); } catch (FolderClosedException ex) { throw ex; } catch (Throwable ex) { System.out.println( String.format("Error while reading mail part: %s", part.getClass().toString())); } } }
private static Content getJoinedContent(MimePart part) throws IOException, MessagingException { Content result = new Content(); MimeMultipart mp = (MimeMultipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { MimeBodyPart p = (MimeBodyPart) mp.getBodyPart(i); result.merge(processPart(p, part)); } return result; }
public static MimeMessage createMessage( Session session, String subject, String html, String text, Address from, Address[] to, Attachment... attachments) { if (text == null) text = Html.convertHtmlToText(html); MimeMessage msg = createEmptyMimeMessage(session); try { msg.setSubject(subject, charset); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, to); if ((attachments == null || attachments.length == 0)) { // no attachments if (Str.isBlank(html)) { // no html msg.setText(text, charset); return msg; } msg.setContent(createMultipartAlternative(text, html)); return msg; } MimeMultipart multipartMixed = new MimeMultipart("mixed"); if (Str.isBlank(html)) { // no html MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(text, charset); multipartMixed.addBodyPart(textBodyPart); } else { // html MimeBodyPart wrapAlternative = new MimeBodyPart(); wrapAlternative.setContent(createMultipartAlternative(text, html)); multipartMixed.addBodyPart(wrapAlternative); } for (Attachment attachment : attachments) { appendAttachment(multipartMixed, attachment); } msg.setContent(multipartMixed); return msg; } catch (MessagingException ex) { throw new RuntimeException(ex); } }
/** * @param MostrarInforme Abre una ventana con el informe del email * @param SERVIDOR * @param PUERTO */ public boolean sendMailHTML(boolean MostrarInforme, String SERVIDOR, String PUERTO) { if (MostrarInforme) { Informe.setVisible(true); Informe.setAlwaysOnTop(true); } try { Informe.setTitulo("Destino: " + Destinatarios.get(0)); Properties props = new Properties(); props.put("mail.smtp.host", SERVIDOR); // "wo06.wiroos.com" o "smtp.gmail.com" props.setProperty("mail.smtp.starttls.enable", "true"); // props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.port", PUERTO); // "587"); props.setProperty("mail.smtp.user", usuarioCorreo); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); BodyPart texto = new MimeBodyPart(); texto.setText(mensaje); BodyPart adjunto = new MimeBodyPart(); if (!rutaArchivo.equals("")) { adjunto.setDataHandler(new DataHandler(new FileDataSource(rutaArchivo))); adjunto.setFileName(nombreArchivo); } MimeMultipart multiParte = new MimeMultipart(); multiParte.addBodyPart(texto); if (!rutaArchivo.equals("")) { multiParte.addBodyPart(adjunto); } MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(usuarioCorreo)); // Destinatarios varios for (int i = 0; i < Destinatarios.size(); i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(Destinatarios.get(i))); message.setSubject(asunto); } message.setContent(mensaje, "text/html"); Informe.SetConectando(); Transport t = session.getTransport("smtp"); t.connect(usuarioCorreo, password); Informe.SetEnviando(); t.sendMessage(message, message.getAllRecipients()); t.close(); Informe.SetEnviado(true); return true; } catch (Exception e) { e.printStackTrace(); Informe.SetEnviado(false); return false; } }
public static String getBodyPartContentType(MimeMultipart mimeMultipart) throws MessagingException { for (int i = 0; i < mimeMultipart.getCount(); i++) { BodyPart bodyPart = mimeMultipart.getBodyPart(i); // ignore attachment if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { return bodyPart.getContentType(); } } return StringUtils.EMPTY; }
private void sendReplyFromPostmaster(Mail mail, String stringContent) { try { MailAddress notifier = getMailetContext().getPostmaster(); MailAddress senderMailAddress = mail.getSender(); MimeMessage message = mail.getMessage(); // Create the reply message MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); // Create the list of recipients in the Address[] format InternetAddress[] rcptAddr = new InternetAddress[1]; rcptAddr[0] = senderMailAddress.toInternetAddress(); reply.setRecipients(Message.RecipientType.TO, rcptAddr); // Set the sender... reply.setFrom(notifier.toInternetAddress()); // Create the message body MimeMultipart multipart = new MimeMultipart(); // Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(stringContent, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); // Create the list of recipients in our MailAddress format Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(senderMailAddress); // Set additional headers if (reply.getHeader(RFC2822Headers.DATE) == null) { reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new java.util.Date())); } String subject = message.getSubject(); if (subject == null) { subject = ""; } if (subject.indexOf("Re:") == 0) { reply.setSubject(subject); } else { reply.setSubject("Re:" + subject); } reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID()); // Send it off... getMailetContext().sendMail(notifier, recipients, reply); } catch (Exception e) { log("Exception found sending reply", e); } }
public void testHeaders() throws Exception { MimeMultipart smm = generateMultiPartRsa("SHA1withRSA", msg, SMIMESignedGenerator.RFC3851_MICALGS); BodyPart bp = smm.getBodyPart(1); assertEquals( "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data", bp.getHeader("Content-Type")[0]); assertEquals("attachment; filename=\"smime.p7s\"", bp.getHeader("Content-Disposition")[0]); assertEquals("S/MIME Cryptographic Signature", bp.getHeader("Content-Description")[0]); }
@Override protected void verifyMessage(MimeMultipart content) throws Exception { assertEquals(3, content.getCount()); verifyMessage((String) content.getBodyPart(0).getContent()); List<String> expectedTypes = Arrays.asList("text/plain", "text/xml"); for (int i = 0; i < 3; i++) { BodyPart part = content.getBodyPart(i); String type = part.getContentType(); MimeType mt = new MimeType(type); assertTrue(expectedTypes.contains(mt.getPrimaryType() + "/" + mt.getSubType())); } }
/** * Build mail for sending. * * @param record - recipients data line (from '-d') * @return - built email. * @throws Exception */ public MimeMultipart buildMailForSand(CSVRecord record) throws Exception { MimeMultipart multipart = new MimeMultipart(); // Build and add message BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(buildEmailBody(record), "text/html; charset=utf-8"); multipart.addBodyPart(messageBodyPart); // Add attachment for (MimeBodyPart attachment : attachmentsList) { multipart.addBodyPart(attachment); } return multipart; }
private static Content getContentOfBestPart(MimePart part, MimePart parent) throws IOException, MessagingException { MimeBodyPart best = null; MimeMultipart mp = (MimeMultipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { // Prefer HTML if the parent is a multipart/related part which may contain // inline images, because text/plain cannot embed the images. boolean isHtmlPreferred = parent != null && parent.isMimeType(MimeType.MULTIPART_RELATED); best = better((MimeBodyPart) mp.getBodyPart(i), best, isHtmlPreferred); } return processPart(best, part); }
public void multipartMixedTest(MimeBodyPart part1, MimeBodyPart part2) throws Exception { MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(part1); mp.addBodyPart(part2); MimeBodyPart m = new MimeBodyPart(); m.setContent(mp); MimeMultipart smm = generateMultiPartRsa("SHA1withRSA", m, SMIMESignedGenerator.RFC3851_MICALGS); SMIMESigned s = new SMIMESigned(smm); verifySigners(s.getCertificates(), s.getSignerInfos()); AttributeTable attr = ((SignerInformation) s.getSignerInfos().getSigners().iterator().next()) .getSignedAttributes(); Attribute a = attr.get(CMSAttributes.messageDigest); byte[] contentDigest = ASN1OctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets(); mp = (MimeMultipart) m.getContent(); ContentType contentType = new ContentType(mp.getContentType()); String boundary = "--" + contentType.getParameter("boundary"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); LineOutputStream lOut = new LineOutputStream(bOut); Enumeration headers = m.getAllHeaderLines(); while (headers.hasMoreElements()) { lOut.writeln((String) headers.nextElement()); } lOut.writeln(); // CRLF separator lOut.writeln(boundary); writePart(mp.getBodyPart(0), bOut); lOut.writeln(); // CRLF terminator lOut.writeln(boundary); writePart(mp.getBodyPart(1), bOut); lOut.writeln(); lOut.writeln(boundary + "--"); MessageDigest dig = MessageDigest.getInstance("SHA1", BC); assertTrue(Arrays.equals(contentDigest, dig.digest(bOut.toByteArray()))); }
private MimeMultipart getMultipartMessage(DataSource ds) { MimeMultipart mmp; try { mmp = new MimeMultipart(ds); // if it's not a real mimemultipart, getCount crashes, which is too late, so crash here // instead mmp.getCount(); return mmp; } catch (MessagingException e) { logger.info("Can not create multipart."); return null; } }
private static MimeMultipart createMultipartAlternative(String text, String html) throws MessagingException { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(text, charset); MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setText(html, charset, "html"); MimeMultipart multipartAlternative = new MimeMultipart("alternative"); multipartAlternative.addBodyPart(textBodyPart); multipartAlternative.addBodyPart(htmlBodyPart); return multipartAlternative; }