List of usage examples for javax.mail.internet MimeMessage writeTo
@Override public void writeTo(OutputStream os) throws IOException, MessagingException
From source file:mail.MailService.java
/** * Erstellt eine MIME-Mail inkl. Transfercodierung. * @param email/*w ww. j a v a2s .c o m*/ * @throws MessagingException * @throws IOException */ public String createMail3(Mail email, Config config) throws MessagingException, IOException { byte[] mailAsBytes = email.getText(); byte[] outputBytes; // Transfercodierung anwenden if (config.getTranscodeDescription().equals(Config.BASE64)) { outputBytes = encodeBase64(mailAsBytes); } else if (config.getTranscodeDescription().equals(Config.QP)) { outputBytes = encodeQuotedPrintable(mailAsBytes); } else { outputBytes = mailAsBytes; } email.setText(outputBytes); Properties props = new Properties(); props.put("mail.smtp.host", "mail.java-tutor.com"); Session session = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(session); // msg.setHeader("MIME-Version" , "1.0"); // msg.setHeader("Content-Type" , "text/plain"); // Absender InternetAddress addressFrom = new InternetAddress(email.getAbsender()); msg.setFrom(addressFrom); // Empfnger InternetAddress addressTo = new InternetAddress(email.getEmpfaenger()); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject(email.getBetreff()); msg.setSentDate(email.getAbsendeDatum()); msg.setText(Utils.toString(outputBytes)); msg.saveChanges(); // Mail in Ausgabestrom schreiben ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { msg.writeTo(bOut); } catch (IOException e) { System.out.println("Fehler beim Schreiben der Mail in Schritt 3"); throw e; } // String out = bOut.toString(); // int pos1 = out.indexOf("Message-ID"); // int pos2 = out.indexOf("@localhost") + 13; // String output = out.subSequence(0, pos1).toString(); // output += (out.substring(pos2)); return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT, "Content-Transfer-Encoding: " + config.getTranscodeDescription())); }
From source file:davmail.smtp.TestSmtp.java
public void sendAndCheckMessage(MimeMessage mimeMessage, String from, String bcc) throws IOException, MessagingException, InterruptedException { // generate message id mimeMessage.saveChanges();/*w ww . j av a 2s .c o m*/ // mimeMessage.writeTo(System.out); // copy Message-id to references header mimeMessage.addHeader("references", mimeMessage.getHeader("message-id")[0]); if (from != null) { writeLine("MAIL FROM:" + from); } else { writeLine("MAIL FROM:" + session.getEmail()); } readLine(); if (bcc != null) { writeLine("RCPT TO:" + bcc); readLine(); } writeLine("RCPT TO:" + Settings.getProperty("davmail.to")); readLine(); writeLine("DATA"); assertEquals("354 Start mail input; end with <CRLF>.<CRLF>", readLine()); mimeMessage.writeTo(new DoubleDotOutputStream(socketOutputStream)); writeLine(""); writeLine("."); assertEquals("250 Queued mail for delivery", readLine()); // wait for asynchronous message send ExchangeSession.MessageList messages = null; for (int i = 0; i < 5; i++) { messages = session.searchMessages("Sent", session.headerIsEqualTo("references", mimeMessage.getMessageID())); if (messages.size() > 0) { break; } Thread.sleep(1000); } assertEquals(1, messages.size()); ExchangeSession.Message sentMessage = messages.get(0); sentMessage.getMimeMessage().writeTo(System.out); assertEquals(mimeMessage.getDataHandler().getContent(), sentMessage.getMimeMessage().getDataHandler().getContent()); }
From source file:org.xsocket.connection.SimpleSmtpClient.java
public void send(MimeMessage message) throws IOException, MessagingException { IBlockingConnection con = new BlockingConnection(host, port); // read greeting readResponse(con);//from w w w . j a va2 s.c om sendCmd(con, "Helo mailserver"); readResponse(con); if (username != null) { String userPassword = new String( Base64.encodeBase64(new String("\000" + username + "\000" + password).getBytes())); sendCmd(con, "AUTH PLAIN " + userPassword); readResponse(con); } Address sender = message.getFrom()[0]; sendCmd(con, "Mail From: " + sender.toString()); readResponse(con); Address[] tos = message.getRecipients(RecipientType.TO); for (Address to : tos) { sendCmd(con, "Rcpt To: " + to.toString()); readResponse(con); } sendCmd(con, "Data"); readResponse(con); ByteArrayOutputStream os = new ByteArrayOutputStream(); message.writeTo(os); os.close(); String s = new String(os.toByteArray()); con.write(s); con.write("\r\n.\r\n"); sendCmd(con, "Quit"); readResponse(con); con.close(); }
From source file:org.apache.james.mailrepository.jcr.JCRMailRepository.java
/** * Writes the message content to the <code>jcr:content/jcr:data</code> * binary property./*from w w w. java 2 s .c o m*/ * * @param node * mail node * @param message * mail message * @throws MessagingException * if a messaging error occurs * @throws RepositoryException * if a repository error occurs * @throws IOException * if an IO error occurs */ @SuppressWarnings("deprecation") private void setMessage(Node node, final MimeMessage message) throws RepositoryException, IOException { try { node = node.getNode("jcr:content"); } catch (PathNotFoundException e) { node = node.getProperty("jcr:content").getNode(); } PipedInputStream input = new PipedInputStream(); final PipedOutputStream output = new PipedOutputStream(input); new Thread() { public void run() { try { message.writeTo(output); } catch (Exception e) { } finally { try { output.close(); } catch (IOException e) { } } } }.start(); node.setProperty("jcr:data", input); }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context/* w w w .j a v a2 s .co m*/ * * @return id for the current message * @throws Exception */ private String writeUsingSMTP(MessageContext msgContext) throws Exception { String id = (new java.rmi.server.UID()).toString(); String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST); SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS); String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message reqMessage = msgContext.getRequestMessage(); msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action); msg.setDisposition(MimePart.INLINE); msg.setSubject(id); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); reqMessage.writeTo(out); msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(fromAddress); System.out.print(client.getReplyString()); client.addRecipient(toAddress); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); return id; }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender, PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData, PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) { if (peppolEndpointData.getCommonName() == null) { throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData); }/*from w w w . j a v a 2 s .co m*/ X509Certificate ourCertificate = keystoreManager.getOurCertificate(); SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(), ourCertificate); MimeMessage signedMimeMessage = null; Mic mic = null; try { MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream, new MimeType("application/xml")); mic = MimeMessageHelper.calculateMic(mimeBodyPart); log.debug("Outbound MIC is : " + mic.toString()); signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart); } catch (MimeTypeParseException e) { throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e); } String endpointAddress = peppolEndpointData.getUrl().toExternalForm(); HttpPost httpPost = new HttpPost(endpointAddress); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { signedMimeMessage.writeTo(byteArrayOutputStream); } catch (Exception e) { throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream"); } httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString()); try { httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(), PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString()); } catch (InvalidAs2SystemIdentifierException e) { throw new IllegalArgumentException( "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData); } httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no"); httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(), As2DispositionNotificationOptions.getDefault().toString()); httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION); httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS"); TransmissionId transmissionId = new TransmissionId(); httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString()); httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date())); // Inserts the S/MIME message to be posted. // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header try { String contentType = signedMimeMessage.getContentType(); ContentType ct = ContentType.create(contentType); httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct)); } catch (Exception ex) { throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage()); } CloseableHttpResponse postResponse = null; // EXECUTE !!!! try { CloseableHttpClient httpClient = createCloseableHttpClient(); log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type " + peppolDocumentTypeId); postResponse = httpClient.execute(httpPost); } catch (HttpHostConnectException e) { throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress); } catch (Exception e) { throw new IllegalStateException( "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(), e); } if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode() + " from " + endpointAddress); throw handleFailedRequest(postResponse); } // handle normal HTTP OK response log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress + " returned HTTP OK, verify MDN response"); MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData); // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields(); String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST); if (messageDigestAsBase64 == null) { messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes())); } String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP); Date receptionTimeStamp = null; if (receptionTimeStampAsString != null) { receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString); } else { receptionTimeStamp = new Date(); } // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString()); @NotNull As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence( EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage, new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64), transmissionId); ByteArrayOutputStream evidenceBytes; try { evidenceBytes = new ByteArrayOutputStream(); IOUtils.copy(evidence.getInputStream(), evidenceBytes); } catch (IOException e) { throw new IllegalStateException( "Unable to transform transport evidence to byte array." + e.getMessage(), e); } return new SendResult(transmissionId, evidenceBytes.toByteArray()); }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(// w w w .j a v a 2 s . c o m "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:org.apache.james.core.MimeMessageWrapper.java
public MimeMessageWrapper(MimeMessage original) throws MessagingException { this(Session.getDefaultInstance(System.getProperties())); flags = original.getFlags();/*from w w w . ja va 2 s.c om*/ if (source == null) { InputStream in; boolean useMemoryCopy = false; String memoryCopy = System.getProperty(USE_MEMORY_COPY); if (memoryCopy != null) { useMemoryCopy = Boolean.valueOf(memoryCopy); } try { if (useMemoryCopy) { ByteArrayOutputStream bos; int size = original.getSize(); if (size > 0) { bos = new ByteArrayOutputStream(size); } else { bos = new ByteArrayOutputStream(); } original.writeTo(bos); bos.close(); in = new SharedByteArrayInputStream(bos.toByteArray()); parse(in); in.close(); saved = true; } else { MimeMessageInputStreamSource src = new MimeMessageInputStreamSource( "MailCopy-" + UUID.randomUUID().toString()); OutputStream out = src.getWritableOutputStream(); original.writeTo(out); out.close(); source = src; } } catch (IOException ex) { // should never happen, but just in case... throw new MessagingException("IOException while copying message", ex); } } }
From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java
@DirtiesContext @Test//from w w w . j av a 2 s.co m public void testMarshal() throws Exception { Assert.assertNotNull(testShsMessage); resultEndpoint.expectedMessageCount(1); template.sendBody("direct:marshal", testShsMessage); resultEndpoint.assertIsSatisfied(); List<Exchange> exchanges = resultEndpoint.getReceivedExchanges(); Exchange exchange = exchanges.get(0); InputStream mimeStream = exchange.getIn().getBody(InputStream.class); MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream); String[] mimeSubject = mimeMessage.getHeader("Subject"); Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]), "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]); Assert.assertNull(mimeMessage.getMessageID()); MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent(); Assert.assertEquals(multipart.getCount(), 2); BodyPart bodyPart = multipart.getBodyPart(1); String content = (String) bodyPart.getContent(); Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY); String contentType = bodyPart.getContentType(); Assert.assertTrue( StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE), "Content type error"); String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding"); Assert.assertNotNull(encodings); Assert.assertEquals(encodings.length, 1); Assert.assertEquals(encodings[0].toUpperCase(), ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase()); mimeMessage.writeTo(System.out); }
From source file:org.exjello.mail.Exchange2003Connection.java
private RequestEntity createMessageEntity(MimeMessage message) throws Exception { final File tempFile = File.createTempFile("exmail", null, null); tempFile.deleteOnExit();/*from w w w. jav a2 s. c o m*/ OutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile)); message.writeTo(output); if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Message Content:"); message.writeTo(log); log.println(); log.flush(); } output.flush(); output.close(); InputStream stream = new FileInputStream(tempFile) { public void close() throws IOException { try { super.close(); } finally { try { if (!tempFile.delete()) tempFile.deleteOnExit(); } catch (Exception ignore) { } } } }; return new InputStreamRequestEntity(stream, tempFile.length(), MESSAGE_CONTENT_TYPE); }