List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java
public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception { final String from = request.getFrom(); if (null == from) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from"); }// w ww .j a v a2s .c om final String to = request.getTo(); if (null == to) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to"); } response.setSuccess(false); final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>(); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { log.debug("Build mime message"); addRecipients(mimeMessage, Message.RecipientType.TO, to); addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc()); addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc()); addReplyTo(mimeMessage, request.getReplyTo()); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject(request.getSubject()); // mimeMessage.setText(request.getText()); List<String> attachments = request.getAttachmentUrls(); MimeMultipart mp = new MimeMultipart(); MimeBodyPart mailBody = new MimeBodyPart(); mailBody.setText(request.getText()); mp.addBodyPart(mailBody); if (null != attachments && !attachments.isEmpty()) { for (String url : attachments) { log.debug("add mime part for {}", url); MimeBodyPart part = new MimeBodyPart(); String filename = url; int pos = filename.lastIndexOf('/'); if (pos >= 0) { filename = filename.substring(pos + 1); } pos = filename.indexOf('?'); if (pos >= 0) { filename = filename.substring(0, pos); } part.setFileName(filename); String fixedUrl = url; if (fixedUrl.startsWith("../")) { fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3); } fixedUrl = fixedUrl.replace(" ", "%20"); part.setDataHandler(new DataHandler(new URL(fixedUrl))); mp.addBodyPart(part); } } mimeMessage.setContent(mp); log.debug("message {}", mimeMessage); } }; try { if (request.isSendMail()) { mailSender.send(preparator); cleanAttachmentConnection(attachmentConnections); log.debug("mail sent"); } if (request.isSaveMail()) { MimeMessage mimeMessage = new MimeMessage((Session) null); preparator.prepare(mimeMessage); // overwrite multipart body as we don't need the attachments mimeMessage.setText(request.getText()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); // add document in referral Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS); List<InternalFeature> features = vectorLayerService.getFeatures( KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null, VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES); InternalFeature orgReferral = features.get(0); log.debug("Got referral {}", request.getReferralId()); InternalFeature referral = orgReferral.clone(); List<InternalFeature> newFeatures = new ArrayList<InternalFeature>(); newFeatures.add(referral); Map<String, Attribute> attributes = referral.getAttributes(); OneToManyAttribute orgComments = (OneToManyAttribute) attributes .get(KtunaxaConstant.ATTRIBUTE_COMMENTS); List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue()); AssociationValue emailAsComment = new AssociationValue(); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE, "Mail: " + request.getSubject()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY, securitycontext.getUserName()); emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date()); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT, new String(baos.toByteArray())); emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false); comments.add(emailAsComment); OneToManyAttribute newComments = new OneToManyAttribute(comments); attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments); log.debug("Going to add mail as comment to referral"); vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features, newFeatures); } response.setSuccess(true); } catch (MailException me) { log.error("Could not send e-mail", me); throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail"); } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * //from w ww . j a v a 2 s.c o m * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from, String to, String cc, String bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && !cc.equals("")) msg.setRecipients(Message.RecipientType.CC, cc); if (bcc != null && !bcc.equals("")) msg.setRecipients(Message.RecipientType.BCC, bcc); msg.addRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "iso-8859-1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(alternativeTextMessage); multiPart.addBodyPart(bodyPart); bodyPart = new MimeBodyPart(); bodyPart.setContent(htmlMessage, "text/html"); multiPart.addBodyPart(bodyPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }
From source file:bioLockJ.module.agent.MailAgent.java
private BodyPart getAttachment(final String filePath) throws Exception { try {/*from ww w. ja va 2s .c om*/ final DataSource source = new FileDataSource(filePath); final File logFile = new File(filePath); final double fileSize = logFile.length() / 1000000; if (fileSize < emailMaxAttachmentMB) { final BodyPart attachPart = new MimeBodyPart(); attachPart.setDataHandler(new DataHandler(source)); attachPart.setFileName(filePath.substring(filePath.lastIndexOf(File.separator) + 1)); return attachPart; } else { Log.out.warn("File [" + filePath + "] too large to attach. Max file size configured in prop file set to = " + emailMaxAttachmentMB + " MB"); } } catch (final Exception ex) { Log.out.error("Unable to attach file", ex); } return null; }
From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java
protected void send(String subject, String content, String contentType) throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", getHost()); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false);//from w ww . j a va 2 s.c o m Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr")); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "utf-8"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); List<String> fileNames = getAtchFileIds(); for (Iterator<String> it = fileNames.iterator(); it.hasNext();) { MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(it.next()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : mp.addBodyPart(mbp2); } // add the Multipart to the message message.setContent(mp); for (Iterator<String> it = getReceivers().iterator(); it.hasNext();) message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next())); transport.connect(getHost(), getPort(), getUsername(), getPassword()); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
From source file:com.medsavant.mailer.Mail.java
public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) { try {/*from www. j a v a 2 s . c om*/ if (src == null || pw == null || host == null || port == -1) { return false; } if (to.isEmpty()) { return false; } LOG.info("Sending email to " + to + " with subject " + subject); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.user", src); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.auth", auth); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", fallback); Session session = Session.getInstance(props, null); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(src, srcName)); InternetAddress[] address = InternetAddress.parse(to); msg.setRecipients(Message.RecipientType.BCC, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(text, "text/html"); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (attachment != null) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); mp.addBodyPart(mbp2); } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // send the message Transport transport = session.getTransport("smtp"); transport.connect(host, src, pw); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); LOG.info("Mail sent"); return true; } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); return false; } }
From source file:org.unitime.commons.Email.java
public void setText(String message) throws MessagingException { MimeBodyPart text = new MimeBodyPart(); text.setContent(message, "text/plain; charset=UTF-8"); iBody.addBodyPart(text);/*from w w w. j a va 2 s . c o m*/ }
From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java
@Override public void send(String subject, String body, String sender) { try {/*from w ww . j a v a 2s. c o m*/ final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(), ','); subject = subjectPrefix + subject; body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix; InternetAddress from = new InternetAddress(this.sender); InternetAddress replyTo = new InternetAddress(sender); Properties p = new Properties(); p.put("mail.smtp.host", smtpHost); p.put("mail.smtp.port", smtpPort); p.put("mail.smtp.starttls.enable", "true"); p.put("mail.smtp.auth", "true"); MailAuthenticator authenticator = new MailAuthenticator(userName, password); Session sendMailSession = Session.getInstance(p, authenticator); MimeMessage msg = new MimeMessage(sendMailSession); msg.setFrom(from); msg.setReplyTo(new Address[] { replyTo }); msg.addRecipients(Message.RecipientType.TO, recipientList); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(body, "text/html; charset=utf-8"); mainPart.addBodyPart(html); msg.setContent(mainPart); Transport.send(msg); LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients); } catch (Exception e) { throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e); } }
From source file:org.wandora.piccolo.actions.SendEmail.java
public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Application application) {//www. ja v a 2s .c om try { Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (subject != null) message.setSubject(subject); if (from != null) message.setFrom(new InternetAddress(from)); Vector<String> recipients = new Vector<String>(); if (recipient != null) { String[] rs = recipient.split(","); String r = null; for (int i = 0; i < rs.length; i++) { r = rs[i]; if (r != null) recipients.add(r); } } MimeMultipart multipart = new MimeMultipart(); Template template = application.getTemplate(emailTemplate, user); HashMap context = new HashMap(); context.put("request", request); context.put("message", message); context.put("recipients", recipients); context.put("emailhelper", new MailHelper()); context.put("multipart", multipart); context.putAll(application.getDefaultContext(user)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); template.process(context, baos); MimeBodyPart mimeBody = new MimeBodyPart(); mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType()); // mimeBody.setContent(baos.toByteArray(),template.getMimeType()); multipart.addBodyPart(mimeBody); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(smtpServer, smtpUser, smtpPass); Address[] recipientAddresses = new Address[recipients.size()]; for (int i = 0; i < recipientAddresses.length; i++) { recipientAddresses[i] = new InternetAddress(recipients.elementAt(i)); } transport.sendMessage(message, recipientAddresses); } catch (Exception e) { logger.writelog("WRN", e); } }
From source file:voldemort.coordinator.HttpGetRequestExecutor.java
public void writeResponse(List<Versioned<byte[]>> versionedValues) throws Exception { MimeMultipart multiPart = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (Versioned<byte[]> versionedValue : versionedValues) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String serializedVectorClock = CoordinatorUtils.getSerializedVectorClock(vectorClock); // Create the individual body part for each versioned value of the // requested key MimeBodyPart body = new MimeBodyPart(); try {/*from ww w . j a v a 2s . c o m*/ // Add the right headers body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVectorClock); body.setContent(responseValue, "application/octet-stream"); body.addHeader(CONTENT_LENGTH, "" + responseValue.length); multiPart.addBodyPart(body); } catch (MessagingException me) { logger.error("Exception while constructing body part", me); outputStream.close(); throw me; } } try { multiPart.writeTo(outputStream); } catch (Exception e) { logger.error("Exception while writing multipart to output stream", e); outputStream.close(); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); if (logger.isDebugEnabled()) { logger.debug("Response = " + response); } // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); }
From source file:org.unitime.commons.JavaMailWrapper.java
@Override public void setBody(String message, String type) throws MessagingException { MimeBodyPart text = new MimeBodyPart(); text.setContent(message, type);/*from www .ja v a 2s . c o m*/ iBody.addBodyPart(text); }