List of usage examples for javax.mail BodyPart setFileName
public void setFileName(String filename) throws MessagingException;
From source file:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject/*ww w . ja v a 2s. c o m*/ * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Prepares message prior to be sent via execute()-method, i.e. sets * properties such as protocol, authentication, etc. * * @return Message-object to be sent to execute()-method * @throws MessagingException/* www .jav a2s. c o m*/ * when problems constructing or sending the mail occur * @throws IOException * when the mail content can not be read or truststore problems * are detected */ public Message prepareMessage() throws MessagingException, IOException { Properties props = new Properties(); String protocol = getProtocol(); // set properties using JAF props.setProperty("mail." + protocol + ".host", smtpServer); props.setProperty("mail." + protocol + ".port", getPort()); props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication)); // set timeout props.setProperty("mail." + protocol + ".timeout", getTimeout()); props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout()); if (useStartTLS || useSSL) { try { String allProtocols = StringUtils .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " "); logger.info("Use ssl/tls protocols for mail: " + allProtocols); props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols); } catch (Exception e) { logger.error("Problem setting ssl/tls protocols for mail", e); } } if (enableDebug) { props.setProperty("mail.debug", "true"); } if (useStartTLS) { props.setProperty("mail.smtp.starttls.enable", "true"); if (enforceStartTLS) { // Requires JavaMail 1.4.2+ props.setProperty("mail.smtp.starttls.require", "true"); } } if (trustAllCerts) { if (useSSL) { props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false"); } } else if (useLocalTrustStore) { File truststore = new File(trustStoreToUse); logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse); logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (useSSL) { // Requires JavaMail 1.4.2+ props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { // Requires JavaMail 1.4.2+ props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtp.ssl.socketFactory.fallback", "false"); } } session = Session.getInstance(props, null); Message message; if (sendEmlMessage) { message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage))); } else { message = new MimeMessage(session); // handle body and attachments Multipart multipart = new MimeMultipart(); final int attachmentCount = attachments.size(); if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) { if (attachmentCount == 1) { // i.e. mailBody is empty File first = attachments.get(0); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } else { message.setText(mailBody); } } else { BodyPart body = new MimeBodyPart(); body.setText(mailBody); multipart.addBodyPart(body); for (File f : attachments) { BodyPart attach = new MimeBodyPart(); attach.setFileName(f.getName()); attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath()))); multipart.addBodyPart(attach); } message.setContent(multipart); } } // set from field and subject if (null != sender) { message.setFrom(new InternetAddress(sender)); } if (null != replyTo) { InternetAddress[] to = new InternetAddress[replyTo.size()]; message.setReplyTo(replyTo.toArray(to)); } if (null != subject) { message.setSubject(subject); } if (receiverTo != null) { InternetAddress[] to = new InternetAddress[receiverTo.size()]; receiverTo.toArray(to); message.setRecipients(Message.RecipientType.TO, to); } if (receiverCC != null) { InternetAddress[] cc = new InternetAddress[receiverCC.size()]; receiverCC.toArray(cc); message.setRecipients(Message.RecipientType.CC, cc); } if (receiverBCC != null) { InternetAddress[] bcc = new InternetAddress[receiverBCC.size()]; receiverBCC.toArray(bcc); message.setRecipients(Message.RecipientType.BCC, bcc); } for (int i = 0; i < headerFields.size(); i++) { Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; }
From source file:com.emc.kibana.emailer.KibanaEmailer.java
private static void sendFileEmail(String security) { final String username = smtpUsername; final String password = smtpPassword; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); if (security.equals(SMTP_SECURITY_TLS)) { properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", smtpPort); } else if (security.equals(SMTP_SECURITY_SSL)) { properties.put("mail.smtp.socketFactory.port", smtpPort); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", smtpPort); }//from w ww .ja va2 s . c om Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(sourceAddress)); // Set To: header field of the header. for (String destinationAddress : destinationAddressList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress)); } // Set Subject: header field message.setSubject(mailTitle); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); StringBuffer bodyBuffer = new StringBuffer(mailBody); if (!kibanaUrls.isEmpty()) { bodyBuffer.append("\n\n"); } // Add urls info to e-mail for (Map<String, String> kibanaUrl : kibanaUrls) { // Add urls to e-mail String urlName = kibanaUrl.get(NAME_KEY); String reportUrl = kibanaUrl.get(URL_KEY); if (urlName != null && reportUrl != null) { bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n"); } } // Fill the message messageBodyPart.setText(bodyBuffer.toString()); // Create a multipart message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachments for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) { messageBodyPart = new MimeBodyPart(); String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY); String filename = kibanaScreenCapture.get(FILE_NAME_KEY); DataSource source = new FileDataSource(absoluteFilename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); logger.info("Sent mail message successfully"); } catch (MessagingException mex) { throw new RuntimeException(mex); } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc, String subject, String body, List<MailFile> mailFiles) throws MessagingException, UnsupportedEncodingException { Message jxMessage = new MimeMessage(_imapConnection.getSession()); jxMessage.setFrom(new InternetAddress(sender, personalName)); jxMessage.addRecipients(Message.RecipientType.TO, to); jxMessage.addRecipients(Message.RecipientType.CC, cc); jxMessage.addRecipients(Message.RecipientType.BCC, bcc); jxMessage.setSentDate(new Date()); jxMessage.setSubject(subject);/*w w w . j a v a 2s . c o m*/ MimeMultipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8); multipart.addBodyPart(messageBodyPart); if (mailFiles != null) { for (MailFile mailFile : mailFiles) { File file = mailFile.getFile(); if (!file.exists()) { continue; } DataSource dataSource = new FileDataSource(file); BodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(mailFile.getFileName()); multipart.addBodyPart(attachmentBodyPart); } } jxMessage.setContent(multipart); return jxMessage; }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }/*from w w w . ja v a 2 s.c o m*/ String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:checkwebsite.Mainframe.java
/** * * @param email/*w ww .j a va 2s.c o m*/ * @param msg */ protected void notify(String email, String msg) { // Recipient's email ID needs to be mentioned. String to = email;//change accordingly // go to link below and turn on Access for less secure apps //https://www.google.com/settings/security/lesssecureapps // Sender's email ID needs to be mentioned String from = "";//Enter your email id here final String username = "";//Enter your email id here final String password = "";//Enter your password here // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Report of your website : " + wurl); // // Now set the actual message // message.setText("Hello, " + msg + " this is sample for to check send " // + "email using JavaMailAPI "); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Now set the actual message messageBodyPart.setText("Please! find your website report in attachment"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "WebsiteReport.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); lblWarning.setText("report sent..."); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java
private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal) throws MessagingException { if (appockMail.getBonLivraison() == null) { msg.setContent(contenuFinal, "text/html; charset=utf-8"); } else {/*from w ww . ja va 2 s. c o m*/ BonLivraison bonLivraison = appockMail.getBonLivraison(); Multipart multipart = new MimeMultipart(); BodyPart attachmentBodyPart = new MimeBodyPart(); File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison()); ByteArrayDataSource bds = null; try { bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()), bonLivraison.getMimeType().getLibelle()); } catch (IOException e) { e.printStackTrace(); } attachmentBodyPart.setDataHandler(new DataHandler(bds)); attachmentBodyPart.setFileName(bonLivraison.getNomFichier()); multipart.addBodyPart(attachmentBodyPart); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8"); multipart.addBodyPart(htmlBodyPart); msg.setContent(multipart); } }
From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java
protected void addAttachments(MailTemplate template, WorkItem workItem, Multipart multipart, JCRSessionWrapper session) throws Exception { for (AttachmentTemplate attachmentTemplate : template.getAttachmentTemplates()) { BodyPart attachmentPart = new MimeBodyPart(); // resolve description String description = attachmentTemplate.getDescription(); if (description != null) { attachmentPart.setDescription(evaluateExpression(workItem, description, session)); }/*w w w . j a va2 s . co m*/ // obtain interface to data DataHandler dataHandler = createDataHandler(attachmentTemplate, workItem, session); attachmentPart.setDataHandler(dataHandler); // resolve file name String name = attachmentTemplate.getName(); if (name != null) { attachmentPart.setFileName(evaluateExpression(workItem, name, session)); } else { // fall back on data source DataSource dataSource = dataHandler.getDataSource(); if (dataSource instanceof URLDataSource) { name = extractResourceName(((URLDataSource) dataSource).getURL()); } else { name = dataSource.getName(); } if (name != null) { attachmentPart.setFileName(name); } } multipart.addBodyPart(attachmentPart); } }
From source file:org.apache.camel.component.mail.MailBinding.java
protected void addAttachmentsToMultipart(MimeMultipart multipart, String partDisposition, Exchange exchange) throws MessagingException { LOG.trace("Adding attachments +++ start +++"); int i = 0;/*w w w .jav a 2 s . co m*/ for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) { String attachmentFilename = entry.getKey(); DataHandler handler = entry.getValue(); if (LOG.isTraceEnabled()) { LOG.trace("Attachment #" + i + ": Disposition: " + partDisposition); LOG.trace("Attachment #" + i + ": DataHandler: " + handler); LOG.trace("Attachment #" + i + ": FileName: " + attachmentFilename); } if (handler != null) { if (shouldAddAttachment(exchange, attachmentFilename, handler)) { // Create another body part BodyPart messageBodyPart = new MimeBodyPart(); // Set the data handler to the attachment messageBodyPart.setDataHandler(handler); if (attachmentFilename.toLowerCase().startsWith("cid:")) { // add a Content-ID header to the attachment // must use angle brackets according to RFC: http://www.ietf.org/rfc/rfc2392.txt messageBodyPart.addHeader("Content-ID", "<" + attachmentFilename.substring(4) + ">"); // Set the filename without the cid messageBodyPart.setFileName(attachmentFilename.substring(4)); } else { // Set the filename messageBodyPart.setFileName(attachmentFilename); } LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); if (contentTypeResolver != null) { String contentType = contentTypeResolver.resolveContentType(attachmentFilename); LOG.trace("Attachment #" + i + ": Using content type resolver: " + contentTypeResolver + " resolved content type as: " + contentType); if (contentType != null) { String value = contentType + "; name=" + attachmentFilename; messageBodyPart.setHeader("Content-Type", value); LOG.trace("Attachment #" + i + ": ContentType: " + messageBodyPart.getContentType()); } } // Set Disposition messageBodyPart.setDisposition(partDisposition); // Add part to multipart multipart.addBodyPart(messageBodyPart); } else { LOG.trace("shouldAddAttachment: false"); } } else { LOG.warn("Cannot add attachment: " + attachmentFilename + " as DataHandler is null"); } i++; } LOG.trace("Adding attachments +++ done +++"); }
From source file:fsi_admin.JSmtpConn.java
@SuppressWarnings("rawtypes") private boolean adjuntarArchivo(StringBuffer msj, BodyPart messagebodypart, MimeMultipart multipart, Vector archivos) {//from w w w . ja va 2s . com if (!archivos.isEmpty()) { FileItem actual = null; try { for (int i = 0; i < archivos.size(); i++) { InputStream inputStream = null; try { actual = (FileItem) archivos.elementAt(i); inputStream = actual.getInputStream(); byte[] sourceBytes = IOUtils.toByteArray(inputStream); String name = actual.getName(); messagebodypart = new MimeBodyPart(); ByteArrayDataSource rawData = new ByteArrayDataSource(sourceBytes); DataHandler data = new DataHandler(rawData); messagebodypart.setDataHandler(data); messagebodypart.setFileName(name); multipart.addBodyPart(messagebodypart); //////////////////////////////////////////////// /* messagebodypart = new MimeBodyPart(); DataSource source = new FileDataSource(new File(actual.getName())); byte[] sourceBytes = actual.get(); OutputStream sourceOS = source.getOutputStream(); sourceOS.write(sourceBytes); messagebodypart.setDataHandler(new DataHandler(source)); messagebodypart.setFileName(actual.getName()); multipart.addBodyPart(messagebodypart); */ /////////////////////////////////////////////////////// } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return true; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al cargar adjunto SMTP: " + e.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); msj.append("Error de Entrada/Salida al cargar adjunto SMTP: " + e.getMessage()); return false; } } else return true; }