List of usage examples for javax.mail BodyPart setDataHandler
public void setDataHandler(DataHandler dh) throws MessagingException;
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);//ww w . j a v a2 s . co m multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java
private void sendMessage(final String content) { try {/* ww w . j a v a 2 s .c om*/ MimeMessage msg = new MimeMessage(sessionProvider.get()); msg.setSubject("jFunk E-mail Report"); msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get()); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=UTF-8"); MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif"))); messageBodyPart.setHeader("Content-ID", "<check>"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif"))); messageBodyPart.setHeader("Content-ID", "<error>"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); smtpClientProvider.get().send(msg); int anzahlRecipients = msg.getAllRecipients().length; log.info( "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get()); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } catch (MailException e) { log.error("Error while sending report e-mail", e); } }
From source file:bo.com.offercruzmail.imp.InterpretadorMensajeGenerico.java
protected Multipart enviarPlantilla(boolean plantillaNueva, String idCargar) throws MessagingException, IOException { String nombreArchivoOrigen;/*ww w. jav a2 s . com*/ String nombreAdjunto; List<T> lista = null; mensajesError = null; T entidad = null; getObjetoNegocio().setIdUsuario(idUsuario); getObjetoNegocio().setComandoPermiso(nombreEntidad); try { if (!plantillaNueva) { if ("todos".equals(idCargar)) { lista = getObjetoNegocio().obtenerTodos(); nombreArchivoOrigen = nombreEntidad + "-" + "lista"; nombreAdjunto = "lista_" + nombreEntidad + ".xlsx"; } else { ID id; try { id = convertirId(idCargar); } catch (Exception ex) { return FormadorMensajes.enviarIdCargarNoValido(); } entidad = getObjetoNegocio().recuperarPorId(id); if (entidad == null) { return FormadorMensajes.enviarEntidadNoExiste(idCargar); } nombreArchivoOrigen = nombreEntidad; nombreAdjunto = nombreEntidad + "_" + idCargar + ".xlsx"; } } else { nombreArchivoOrigen = nombreEntidad; nombreAdjunto = "plantilla_" + nombreEntidad + ".xlsx"; // if (this instanceof IInterpretadorFormularioDasometrico) { // if (cargarPlantillaFormularios) { // nombreArchivoOrigen = "plantillafrm"; // } // } } String nombreArchivoOriginal = "plantillas/" + nombreArchivoOrigen + ".xlsx"; File archivoCopia = UtilitariosMensajes.reservarNombre(nombreEntidad); UtilitariosMensajes.copiarArchivo(new File(nombreArchivoOriginal), archivoCopia); archivosTemporales.add(archivoCopia); FileInputStream fis = null; OutputStream os = null; try { Workbook libro; fis = new FileInputStream(archivoCopia); libro = WorkbookFactory.create(fis); hojaActual = new HojaExcelHelper(libro.getSheetAt(0)); if (plantillaNueva) { preparPlantillaAntesDeEnviar(libro); } else { if (lista != null) { mostrarLista(lista); } else { mostrarEntidad(entidad, libro); } } if (mensajesError != null) { return FormadorMensajes.enviarErroresNegocio(mensajesError); } //Guardamos cambio os = new FileOutputStream(archivoCopia); libro.write(os); } catch (InvalidFormatException ex) { } finally { if (fis != null) { fis.close(); } if (os != null) { os.close(); } } String textoMensaje; if (plantillaNueva) { textoMensaje = escapeHtml4("La plantilla est adjunta a este mensaje."); } else if (lista != null) { textoMensaje = "La consulta ha devuelto " + lista.size() + " registro(s)."; } else { textoMensaje = escapeHtml4("El registro solicitado est adjunto a este mensaje"); } Multipart cuerpo = new MimeMultipart(); BodyPart adjunto = new MimeBodyPart(); DataSource origen = new FileDataSource(archivoCopia); adjunto.setDataHandler(new DataHandler(origen)); adjunto.setFileName(nombreAdjunto); cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(textoMensaje)); cuerpo.addBodyPart(adjunto); return cuerpo; } catch (PermisosInsuficientesException ex) { appendException(new BusinessExceptionMessage(ex.getMessage(), "Autentificacion")); } if (mensajesError != null) { return FormadorMensajes.enviarErroresNegocio(mensajesError); } return null; }
From source file:immf.ImodeForwardMail.java
private void attacheFile() throws EmailException { try {//w ww . ja va2s. com List<AttachedFile> files = this.imm.getAttachFileList(); for (AttachedFile f : files) { BodyPart part = createBodyPart(); part.setDataHandler(new DataHandler(new ByteArrayDataSource(f.getData(), f.getContentType()))); Util.setFileName(part, f.getFilename(), this.charset, null); part.setDisposition(BodyPart.ATTACHMENT); getContainer().addBodyPart(part); } } catch (Exception e) { throw new EmailException(e); } }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public MimeMessageHelper addAttachment(String name, String type, byte[] content) throws MessagingException { BodyPart attachmentPart = new MimeBodyPart(); ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(content, type); attachmentPart.setDataHandler(new DataHandler(byteArrayDataSource)); attachmentPart.setFileName(name);/* w w w . ja va2 s.c om*/ attachmentPart.setDisposition(Part.ATTACHMENT); attachments.add(attachmentPart); return this; }
From source file:pt.ist.fenix.api.SupportFormResource.java
private void sendEmail(String from, String subject, String body, SupportBean bean) { Properties props = new Properties(); props.put("mail.smtp.host", Objects .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {//from w ww .j a v a 2 s .c o m message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress())); message.setSubject(subject); message.setText(body); Multipart multipart = new MimeMultipart(); { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } if (!Strings.isNullOrEmpty(bean.attachment)) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType))); messageBodyPart.setFileName(bean.fileName); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); Transport.send(message); } catch (Exception e) { logger.error("Could not send support email! Original message was: " + body, e); } }
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }// w ww .j a v a2 s . c o m if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;//from w w w . jav a2 s . c o m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException { Properties props = new Properties(); //props.setProperty("mail.debug", "true"); props.setProperty("mail.smtp.host", emailHost); if (emailUser != null) { props.setProperty("mail.smtp.auth", "true"); }/*from ww w . jav a 2s. com*/ Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass); Session mailSession = Session.getDefaultInstance(props, emailAuthenticator); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); // transport.connect(emailHost, emailUser, emailPass); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {/*from ww w .j a va 2s .c om*/ // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }