javax.mail.BodyPart Java Examples
The following examples show how to use
javax.mail.BodyPart.
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: EmailStepsTest.java From datamill with ISC License | 6 votes |
public void sendMail(String to, String from, String subject, String text) { Session session = Session.getDefaultInstance(setupSmtpProperties()); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(text, "text/html"); MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(messageBodyPart); message.setContent(mimeMultipart); Transport.send(message); } catch (MessagingException e) { logger.error("Could not send mail", e); } }
Example #2
Source File: MailSteps.java From NoraUi with GNU Affero General Public License v3.0 | 6 votes |
/** * @param mimeMultipart * @return * @throws MessagingException * @throws IOException */ private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException { final StringBuilder result = new StringBuilder(); final int count = mimeMultipart.getCount(); for (int i = 0; i < count; i++) { final BodyPart bodyPart = mimeMultipart.getBodyPart(i); if (bodyPart.isMimeType("text/plain")) { result.append("\n"); result.append(bodyPart.getContent()); } else if (bodyPart.isMimeType("text/html")) { result.append("\n"); result.append((String) bodyPart.getContent()); } else if (bodyPart.getContent() instanceof MimeMultipart) { result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent())); } } return result.toString(); }
Example #3
Source File: MailUtil.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Send a calendar message. * * @param mail * The mail to send * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occurred during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException { Message msg = prepareMessage( mail, session ); msg.setHeader( HEADER_NAME, HEADER_VALUE ); MimeMultipart multipart = new MimeMultipart( ); BodyPart msgBodyPart = new MimeBodyPart( ); msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ), AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) ); multipart.addBodyPart( msgBodyPart ); BodyPart calendarBodyPart = new MimeBodyPart( ); calendarBodyPart.setContent( mail.getCalendarMessage( ), AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR ) + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) ); calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 ); multipart.addBodyPart( calendarBodyPart ); msg.setContent( multipart ); sendMessage( msg, transport ); }
Example #4
Source File: AssertAttachment.java From ogham with Apache License 2.0 | 6 votes |
private static void assertEquals(ExpectedAttachment expected, BodyPart attachment, AssertionRegistry registry) throws Exception { // @formatter:off String prefix = "attachment named '" + expected.getName() + "'" + (attachment==null ? " (/!\\ not found)" : ""); String contentType = attachment == null || attachment.getContentType()==null ? null : attachment.getContentType(); registry.register(() -> Assert.assertTrue(prefix + " mimetype should match '" + expected.getMimetype() + "' but was " + (contentType==null ? "null" : "'" + contentType + "'"), contentType!=null && expected.getMimetype().matcher(contentType).matches())); registry.register(() -> Assert.assertEquals(prefix + " description should be '" + expected.getDescription() + "'", expected.getDescription(), attachment == null ? null : attachment.getDescription())); registry.register(() -> Assert.assertEquals(prefix + " disposition should be '" + expected.getDisposition() + "'", expected.getDisposition(), attachment == null ? null : attachment.getDisposition())); registry.register(() -> Assert.assertArrayEquals(prefix + " has invalid content", expected.getContent(), attachment == null ? null : getContent(attachment))); // @formatter:on }
Example #5
Source File: PendenzeController.java From govpay with GNU General Public License v3.0 | 6 votes |
private String getBodyPartFileName (BodyPart bodyPart) throws Exception{ String partName = null; String[] headers = bodyPart.getHeader(BaseController.PARAMETRO_CONTENT_DISPOSITION); if(headers != null && headers.length > 0){ String header = headers[0]; // in due parti perche il suffisso con solo " imbrogliava il controllo int prefixIndex = header.indexOf(BaseController.PREFIX_FILENAME); if(prefixIndex > -1){ partName = header.substring(prefixIndex + BaseController.PREFIX_FILENAME.length()); int suffixIndex = partName.indexOf(BaseController.SUFFIX_FILENAME); partName = partName.substring(0,suffixIndex); } } return partName; }
Example #6
Source File: MimePackage.java From ats-framework with Apache License 2.0 | 6 votes |
/** * Check if the body is from the content type and returns it if not attachment * * @param mimePart * @param contentType * @return null if not with specific content type or part is attachment */ private String getBodyIfNotAttachment( BodyPart mimePart, String contentType ) throws MessagingException, IOException { String mimePartContentType = mimePart.getContentType().toLowerCase(); if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type String contentDisposition = mimePart.getDisposition(); if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) { Object partContent = mimePart.getContent(); if (partContent instanceof InputStream) { return IoUtils.streamToString((InputStream) partContent); } else { return partContent.toString(); } } } return null; }
Example #7
Source File: MailEncoderTest.java From vertx-mail-client with Apache License 2.0 | 6 votes |
@Test public void testAttachment() throws Exception { MailMessage message = new MailMessage(); MailAttachment attachment = MailAttachment.create(); attachment.setContentType("application/x-something") .setData(Buffer.buffer("***")) .setDescription("description") .setDisposition("attachment") .setName("file.txt"); message.setAttachment(attachment); String mime = new MailEncoder(message, HOSTNAME).encode(); assertThat(mime, containsString("Content-Type: application/x-something; name=\"file.txt\"")); assertThat(mime, containsString("Content-Description: description")); assertThat(mime, containsString("Content-Disposition: attachment; filename=\"file.txt\"")); BodyPart part = ((MimeMultipart) TestUtils.getMessage(mime).getContent()).getBodyPart(0); assertEquals("***", TestUtils.inputStreamToString(part.getInputStream())); assertEquals("attachment", part.getDisposition()); assertEquals("file.txt", part.getFileName()); assertEquals("description", part.getDescription()); assertEquals("application/x-something; name=\"file.txt\"", part.getContentType()); }
Example #8
Source File: LargeMessageTest.java From greenmail with Apache License 2.0 | 6 votes |
/** * Retrieve message from retriever and check the attachment and text content * * @param server Server to read from * @param to Account to retrieve */ private void retrieveAndCheck(AbstractServer server, String to) throws MessagingException, IOException { try (Retriever retriever = new Retriever(server)) { Message[] messages = retriever.getMessages(to); assertEquals(1, messages.length); Message message = messages[0]; assertTrue(message.getContentType().startsWith("multipart/mixed")); MimeMultipart body = (MimeMultipart) message.getContent(); assertTrue(body.getContentType().startsWith("multipart/mixed")); assertEquals(2, body.getCount()); // Message text final BodyPart textPart = body.getBodyPart(0); String text = (String) textPart.getContent(); assertEquals(createLargeString(), text); final BodyPart attachment = body.getBodyPart(1); assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file")); InputStream attachmentStream = (InputStream) attachment.getContent(); byte[] bytes = IOUtils.toByteArray(attachmentStream); assertArrayEquals(createLargeByteArray(), bytes); } }
Example #9
Source File: Message.java From OrigamiSMTP with MIT License | 6 votes |
/** Adds a plain text attachment * @param BodyPart */ private void addPlainTextAttachment(BodyPart b) { try { System.out.println("Adding plain text attachment"); String fileName = getFileName(b.getContentType()); String content = (String) b.getContent(); int size = b.getSize(); Attachment attach = new Attachment(fileName, content.getBytes(), size); attachments.add(attach); } catch (MessagingException | IOException e) { System.err.println("Could not get file name or read file content"); e.printStackTrace(); } }
Example #10
Source File: Mailer.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 6 votes |
private static Multipart getMessagePart() throws MessagingException, IOException { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(getVal("msg.Body")); multipart.addBodyPart(messageBodyPart); if (getBoolVal("attach.reports")) { LOG.info("Attaching Reports as zip"); multipart.addBodyPart(getReportsBodyPart()); } else { if (getBoolVal("attach.standaloneHtml")) { multipart.addBodyPart(getStandaloneHtmlBodyPart()); } if (getBoolVal("attach.console")) { multipart.addBodyPart(getConsoleBodyPart()); } if (getBoolVal("attach.screenshots")) { multipart.addBodyPart(getScreenShotsBodyPart()); } } messageBodyPart.setContent(getVal("msg.Body") .concat("\n\n\n") .concat(MailComponent.getHTMLBody()), "text/html"); return multipart; }
Example #11
Source File: MultipartMimeUtils.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
/** * Extract the text content for a {@link BodyPart}, assuming the default * encoding. */ public static String getTextContent(BodyPart part) throws MessagingException, IOException { ContentType contentType = new ContentType(part.getContentType()); String charset = contentType.getParameter("charset"); if (charset == null) { // N.B.(schwardo): The MIME spec doesn't seem to provide a // default charset, but the default charset for HTTP is // ISO-8859-1. That seems like a reasonable default. charset = "ISO-8859-1"; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteStreams.copy(part.getInputStream(), baos); try { return new String(baos.toByteArray(), charset); } catch (UnsupportedEncodingException ex) { return new String(baos.toByteArray()); } }
Example #12
Source File: MailConnection.java From scriptella-etl with Apache License 2.0 | 6 votes |
protected MimeMessage format(Reader reader, PropertiesSubstitutor ps) throws MessagingException, IOException { //Read message body content String text = ps.substitute(reader); //Create message and set headers MimeMessage message = new MimeMessage(session); message.setFrom(InternetAddress.getLocalAddress(session)); if (subject != null) { message.setSubject(ps.substitute(subject)); } //if html content if (TYPE_HTML.equalsIgnoreCase(type)) { BodyPart body = new MimeBodyPart(); body.setContent(text, "text/html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(body); message.setContent(mp); } else { message.setText(text); } return message; }
Example #13
Source File: DefaultMailSender.java From Mario with Apache License 2.0 | 6 votes |
private void sendAndCc(String from, String to, String copyto, String subject, String content) throws AddressException, MessagingException { props.put("mail.smtp.host", smtp); props.put("mail.smtp.auth", "true"); mimeMessage.setSubject(subject); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent("" + content, "text/html;charset=GBK"); multipart.addBodyPart(bodyPart); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto)); mimeMessage.setFrom(new InternetAddress(from)); sendOut(); }
Example #14
Source File: MailUtils.java From scada with MIT License | 6 votes |
/** * ����ʼ��ı����� * @param part �ʼ��� * @param content �洢�ʼ��ı����ݵ��ַ��� */ public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { //������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж� boolean isContainTextAttach = part.getContentType().indexOf("name") > 0; if (part.isMimeType("text/*") && !isContainTextAttach) { content.append(part.getContent().toString()); } else if (part.isMimeType("message/rfc822")) { getMailTextContent((Part)part.getContent(),content); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); getMailTextContent(bodyPart,content); } } }
Example #15
Source File: Mail.java From camunda-bpm-mail with Apache License 2.0 | 6 votes |
protected static void processMessageContent(Message message, Mail mail) throws MessagingException, IOException { if (isMultipartMessage(message)) { Multipart multipart = (Multipart) message.getContent(); int numberOfParts = multipart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { BodyPart bodyPart = multipart.getBodyPart(partCount); processMessagePartContent(bodyPart, mail); } } else { processMessagePartContent(message, mail); } }
Example #16
Source File: NntpUtil.java From scava with Eclipse Public License 2.0 | 6 votes |
private static String getBodyPart(MimeMultipart mimeMultiPart) throws IOException, MessagingException { for(int i=0; i<mimeMultiPart.getCount(); i++) { BodyPart bodyPart = mimeMultiPart.getBodyPart(i); if(bodyPart.isMimeType("text/plain")) { return (String) bodyPart.getContent(); } else if(bodyPart.getContent() instanceof MimeMultipart) { return getBodyPart((MimeMultipart)bodyPart.getContent()); } } return ""; }
Example #17
Source File: ServiceMcaCondition.java From scipio-erp with Apache License 2.0 | 6 votes |
private List<String> getBodyText(Part part) throws MessagingException, IOException { Object c = part.getContent(); if (c instanceof String) { return UtilMisc.toList((String) c); } else if (c instanceof Multipart) { List<String> textContent = new ArrayList<>(); // SCIPIO: switched to ArrayList int count = ((Multipart) c).getCount(); for (int i = 0; i < count; i++) { BodyPart bp = ((Multipart) c).getBodyPart(i); textContent.addAll(this.getBodyText(bp)); } return textContent; } else { return new ArrayList<>(); // SCIPIO: switched to ArrayList } }
Example #18
Source File: EmailUtils.java From ogham with Apache License 2.0 | 5 votes |
/** * Get a list of direct attachments that match the provided predicate. * * @param multipart * the email that contains several parts * @param filter * the predicate used to find the attachments * @return the found attachments or empty list * @throws MessagingException * when message can't be read */ public static List<BodyPart> getAttachments(Multipart multipart, Predicate<Part> filter) throws MessagingException { if (multipart == null) { throw new IllegalStateException("The multipart can't be null"); } List<BodyPart> found = new ArrayList<>(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (filter.test(bodyPart)) { found.add(bodyPart); } } return found; }
Example #19
Source File: ZhilianEmailResumeParser.java From job with MIT License | 5 votes |
protected Document parse2Html(File file) throws Exception { InputStream in = new FileInputStream(file); Session mailSession = Session.getDefaultInstance(System.getProperties(), null); MimeMessage msg = new MimeMessage(mailSession, in); Multipart part = (Multipart) msg.getContent(); String html = ""; for(int i = 0; i < part.getCount(); i++) { BodyPart body = part.getBodyPart(i); String type = body.getContentType(); if(type.startsWith("text/html")) { html = body.getContent().toString(); break; } } in.close(); if(html == null || html.length() == 0) { String content = FileUtils.readFileToString(file); final String endFlag = "</html>"; int start = content.indexOf("<html"); int end = content.indexOf(endFlag); content = content.substring(start, end + endFlag.length()); html = QuotedPrintableUtils.decode(content.getBytes(), "gb2312"); System.err.println(html); } return Jsoup.parse(html); }
Example #20
Source File: DlpDomainRules.java From james-project with Apache License 2.0 | 5 votes |
private Stream<Object> extractContentsComplexType(Object content) throws IOException, MessagingException { if (content instanceof Message) { Message message = (Message) content; return Stream.of(message.getContent()); } if (content instanceof Multipart) { return MultipartUtil.retrieveBodyParts((Multipart) content) .stream() .map(Throwing.function(BodyPart::getContent).sneakyThrow()); } return Stream.of(); }
Example #21
Source File: MailHandler.java From openmeetings with Apache License 2.0 | 5 votes |
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception { log.debug("setMessageBody for iCal message"); // -- Create a new message -- Multipart multipart = new MimeMultipart(); Multipart multiBody = new MimeMultipart("alternative"); BodyPart html = new MimeBodyPart(); html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8"))); multiBody.addBodyPart(html); BodyPart iCalContent = new MimeBodyPart(); iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage"); iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "text/calendar; charset=UTF-8; method=REQUEST"))); multiBody.addBodyPart(iCalContent); BodyPart body = new MimeBodyPart(); body.setContent(multiBody); multipart.addBodyPart(body); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()), "application/ics"))); iCalAttachment.removeHeader("Content-Transfer-Encoding"); iCalAttachment.addHeader("Content-Transfer-Encoding", "base64"); iCalAttachment.removeHeader("Content-Type"); iCalAttachment.addHeader("Content-Type", "application/ics"); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); msg.setContent(multipart); return msg; }
Example #22
Source File: StripAttachmentTest.java From james-project with Apache License 2.0 | 5 votes |
@Test void getFilenameShouldReturnRandomFilenameWhenExceptionOccured() throws Exception { BodyPart bodyPart = mock(BodyPart.class); when(bodyPart.getFileName()) .thenThrow(new MessagingException()); StripAttachment mailet = new StripAttachment(); String filename = mailet.getFilename(bodyPart); assertThat(filename).isNotNull(); }
Example #23
Source File: MailSender.java From iaf with Apache License 2.0 | 5 votes |
private void setAttachments(MailSession mailSession, MimeMessage msg, String messageTypeWithCharset) throws MessagingException { List<MailAttachmentStream> attachmentList = mailSession.getAttachmentList(); String message = mailSession.getMessage(); if (attachmentList == null || attachmentList.size() == 0) { log.debug("no attachments found to attach to mailSession"); msg.setContent(message, messageTypeWithCharset); } else { if(log.isDebugEnabled()) log.debug("found ["+attachmentList.size()+"] attachments to attach to mailSession"); Multipart multipart = new MimeMultipart(); BodyPart messagePart = new MimeBodyPart(); messagePart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messagePart); int counter = 0; for (MailAttachmentStream attachment : attachmentList) { counter++; String name = attachment.getName(); if (StringUtils.isEmpty(name)) { name = getDefaultAttachmentName() + counter; } log.debug("found attachment [" + attachment + "]"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setFileName(name); try { ByteArrayDataSource bads = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType()); bads.setName(attachment.getName()); messageBodyPart.setDataHandler(new DataHandler(bads)); } catch (IOException e) { log.error("error attaching attachment to MailSession", e); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } }
Example #24
Source File: JavaMailWrapper.java From unitime with Apache License 2.0 | 5 votes |
@Override protected void addAttachment(String name, DataHandler data) throws MessagingException { BodyPart attachment = new MimeBodyPart(); attachment.setDataHandler(data); attachment.setFileName(name); attachment.setHeader("Content-ID", "<" + name + ">"); iBody.addBodyPart(attachment); }
Example #25
Source File: MailManager.java From vpn-over-dns with BSD 3-Clause "New" or "Revised" License | 5 votes |
private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed) throws IOException, MessagingException { // content-type: multipart/mixed ou multipart/alternative final StringBuffer selected_content = new StringBuffer(); for (int i = 0; i < multipart.getCount(); i++) { final BodyPart body_part = multipart.getBodyPart(i); final Object content = body_part.getContent(); final String content_string; if (String.class.isInstance(content)) if (body_part.isMimeType("text/html")) content_string = GenericTools.html2Text((String) content); else if (body_part.isMimeType("text/plain")) content_string = (String) content; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to String"); content_string = (String) content; } else if (MimeMultipart.class.isInstance(content)) { boolean part_mixed = false; if (body_part.isMimeType("multipart/mixed")) part_mixed = true; else if (body_part.isMimeType("multipart/alternative")) part_mixed = false; else { log.warn("body part content-type not handled: " + body_part.getContentType() + " -> downgrading to multipart/mixed"); part_mixed = true; } content_string = getMultipartContentString((MimeMultipart) content, part_mixed); } else { log.warn("invalid body part content type and class: " + content.getClass().toString() + " - " + body_part.getContentType()); content_string = ""; } if (mixed == false) { // on sélectionne la première part non vide - ce n'est pas forcément la meilleure alternative, mais comment différentiel un text/plain d'une pièce jointe d'un text/plain du corps du message, accompagnant un text/html du même corps ??? if (selected_content.length() == 0) selected_content.append(content_string); } else { if (selected_content.length() > 0 && content_string.length() > 0) selected_content.append("\r\n---\r\n"); selected_content.append(content_string); } } return selected_content.toString(); }
Example #26
Source File: MailUtil.java From jeecg with Apache License 2.0 | 5 votes |
/** * 发送电子邮件 * * @param smtpHost * 发信主机 * @param receiver * 邮件接收者 * @param title * 邮件的标题 * @param content * 邮件的内容 * @param sender * 邮件发送者 * @param user * 发送者邮箱用户名 * @param pwd * 发送者邮箱密码 * @throws MessagingException */ public static void sendEmail(String smtpHost, String receiver, String title, String content, String sender, String user, String pwd) throws MessagingException { Properties props = new Properties(); props.put("mail.host", smtpHost); props.put("mail.transport.protocol", "smtp"); // props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动! props.put("mail.smtp.auth", "true"); Session s = Session.getDefaultInstance(props); s.setDebug(true); MimeMessage message = new MimeMessage(s); // 给消息对象设置发件人/收件人/主题/发信时间 // 发件人的邮箱 InternetAddress from = new InternetAddress(sender); message.setFrom(from); InternetAddress to = new InternetAddress(receiver); message.setRecipient(Message.RecipientType.TO, to); message.setSubject(title); message.setSentDate(new Date()); // 给消息对象设置内容 BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象 mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码 Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对 // 象(事实上可以存放多个) mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart) message.setContent(mm);// 把mm作为消息对象的内容 message.saveChanges(); Transport transport = s.getTransport("smtp"); transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的 transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
Example #27
Source File: MultiPartEmail.java From commons-email with Apache License 2.0 | 5 votes |
/** * Does the work of actually building the MimeMessage. Please note that * a user rarely calls this method directly and only if he/she is * interested in the sending the underlying MimeMessage without * commons-email. * * @throws EmailException if there was an error. * @since 1.0 */ @Override public void buildMimeMessage() throws EmailException { try { if (primaryBodyPart != null) { // before a multipart message can be sent, we must make sure that // the content for the main body part was actually set. If not, // an IOException will be thrown during super.send(). final BodyPart body = this.getPrimaryBodyPart(); try { body.getContent(); } catch (final IOException e) // NOPMD { // do nothing here. // content will be set to an empty string as a result. // (Should this really be rethrown as an email exception?) // throw new EmailException(e); } } if (subType != null) { getContainer().setSubType(subType); } super.buildMimeMessage(); } catch (final MessagingException me) { throw new EmailException(me); } }
Example #28
Source File: HttpSender.java From iaf with Apache License 2.0 | 5 votes |
public static String handleMultipartResponse(String mimeType, InputStream inputStream, IPipeLineSession session, HttpResponseHandler httpHandler) throws IOException, SenderException { String result = null; try { InputStreamDataSource dataSource = new InputStreamDataSource(mimeType, inputStream); MimeMultipart mimeMultipart = new MimeMultipart(dataSource); for (int i = 0; i < mimeMultipart.getCount(); i++) { BodyPart bodyPart = mimeMultipart.getBodyPart(i); boolean lastPart = mimeMultipart.getCount() == i + 1; if (i == 0) { String charset = Misc.DEFAULT_INPUT_STREAM_ENCODING; ContentType contentType = ContentType.parse(bodyPart.getContentType()); if(contentType.getCharset() != null) charset = contentType.getCharset().name(); InputStream bodyPartInputStream = bodyPart.getInputStream(); result = Misc.streamToString(bodyPartInputStream, charset); if (lastPart) { bodyPartInputStream.close(); } } else { // When the last stream is read the // httpMethod.releaseConnection() can be called, hence pass // httpMethod to ReleaseConnectionAfterReadInputStream. session.put("multipart" + i, new ReleaseConnectionAfterReadInputStream( lastPart ? httpHandler : null, bodyPart.getInputStream())); } } } catch(MessagingException e) { throw new SenderException("Could not read mime multipart response", e); } return result; }
Example #29
Source File: MimeMessageWrapper.java From scipio-erp with Apache License 2.0 | 5 votes |
public String getPartText(String index) { BodyPart part = getPart(index); if (part != null) { try { return getContentText(part.getContent()); } catch (Exception e) { Debug.logError(e, module); return null; } } return null; }
Example #30
Source File: OverrideNameWrapperResourceHandler.java From ogham with Apache License 2.0 | 5 votes |
@Override public void setData(BodyPart part, NamedResource resource, Attachment attachment) throws AttachmentResourceHandlerException { OverrideNameWrapper wrapper = (OverrideNameWrapper) resource; Resource wrapped = wrapper.getDelegate(); // if possible, do not convert to ByteResource if (wrapped instanceof NamedResource) { delegate.setData(part, (NamedResource) wrapped, attachment); return; } try { delegate.setData(part, new ByteResource(wrapper.getName(), wrapper.getInputStream()), attachment); } catch (IOException e) { throw new AttachmentResourceHandlerException("Failed to read the content of the attachment named "+wrapper.getName(), attachment, e); } }