List of usage examples for javax.mail.internet MimeMessage setSubject
@Override public void setSubject(String subject) throws MessagingException
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpEmailFrom"); }/* w w w. j a v a2 s .com*/ smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * /*from ww w .ja va 2 s . c o m*/ * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Hello, \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n\n"); builder.append( "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://" + serverString + "/idp/addUser.jsf.\n"); builder.append( "If you have an account, please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (MessagingException e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Html Email test with attachment"); String html = loadHtml();/* ww w.j a v a 2 s . c om*/ MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.ATTACHMENT); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setContent(html, "text/html; charset=\"UTF-8\""); Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Html Email test with attachment", message.getTitle()); assertEquals(html, message.getBody()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailTextWithAttachment() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(mockListener2); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);/*from ww w. j av a 2 s .com*/ Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Plain text Email test with attachment", message.getTitle()); assertEquals(textEmailContent, message.getBody()); assertEquals(textEmailContent.substring(0, 200), message.getSummary()); assertEquals(ATT_SIZE, message.getAttachmentsSize()); assertEquals(1, message.getAttachments().size()); String path = MessageFormat.format(attachmentPath, messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId())); Attachment attached = message.getAttachments().iterator().next(); assertEquals(path, attached.getPath()); assertEquals("lemonde.html", attached.getFileName()); assertEquals("componentId", message.getComponentId()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals("text/plain", message.getContentType()); org.jvnet.mock_javamail.Mailbox.clearAll(); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); verify(mockListener1, times(2)).getComponentId(); }
From source file:org.xwiki.mail.integration.JavaIntegrationTest.java
@Test public void sendMailWithCustomMessageId() throws Exception { Session session = Session.getInstance(this.configuration.getAllProperties()); MimeMessage message = new MimeMessage(session) { @Override/*from w w w. ja va 2 s .c o m*/ protected void updateMessageID() throws MessagingException { if (getMessageID() == null) { super.updateMessageID(); } } }; message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com")); message.setText("Test message Id support"); message.setHeader("Message-ID", "<custom@domain>"); message.setSubject("subject"); MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory"); this.sender.sendAsynchronously(Arrays.asList(message), session, memoryMailListener); // Verify that the mails have been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 1); MimeMessage[] messages = this.mail.getReceivedMessages(); assertEquals("<custom@domain>", messages[0].getMessageID()); }
From source file:mail.MailService.java
/** * Erstellt eine MIME-Mail inkl. Transfercodierung. * @param email/*from w w w . j a va 2 s . 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:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser, ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpEmailFrom"); }/* w w w.ja va 2s . com*/ smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:com.netflix.genie.server.jobmanager.impl.JobMonitor.java
/** * Check the properties file to figure out if an email * needs to be sent at the end of the job. If yes, get * mail properties and try and send email about Job Status. * @return 0 for success, -1 for failure *///from w w w . j a v a 2 s.c o m private boolean sendEmail(String emailTo) { logger.debug("called"); if (!config.getBoolean("netflix.genie.server.mail.enable", false)) { logger.warn("Email is disabled but user has specified an email address."); return false; } // Sender's email ID String fromEmail = config.getString("netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com"); logger.info("From email address to use to send email: " + fromEmail); // Set the smtp server hostname. Use localhost as default String smtpHost = config.getString("netflix.genie.server.mail.smtp.host", "localhost"); logger.debug("Email smtp server: " + smtpHost); // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); // check whether authentication should be turned on Authenticator auth = null; if (config.getBoolean("netflix.genie.server.mail.smtp.auth", false)) { logger.debug("Email Authentication Enabled"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); String userName = config.getString("netflix.genie.server.mail.smtp.user"); String password = config.getString("netflix.genie.server.mail.smtp.password"); if ((userName == null) || (password == null)) { logger.error("Authentication is enabled and username/password for smtp server is null"); return false; } logger.debug( "Constructing authenticator object with username" + userName + " and password " + password); auth = new SMTPAuthenticator(userName, password); } else { logger.debug("Email authentication not enabled."); } // Get the default Session object. Session session = Session.getInstance(properties, auth); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(fromEmail)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); // Set Subject: header field message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus()); // Now set the actual message String body = "Your Genie Job is complete\n\n" + "Job ID: " + ji.getJobID() + "\n" + "Job Name: " + ji.getJobName() + "\n" + "Status: " + ji.getStatus() + "\n" + "Status Message: " + ji.getStatusMsg() + "\n" + "Output Base URL: " + ji.getOutputURI() + "\n"; message.setText(body); // Send message Transport.send(message); logger.info("Sent email message successfully...."); return true; } catch (MessagingException mex) { logger.error("Got exception while sending email", mex); return false; } }
From source file:com.email.SendEmail.java
/** * Sends a single email and uses account based off of the section that the * email comes from after email is sent the attachments are gathered * together and collated into a single PDF file and a history entry is * created based off of that entry/* ww w . j a v a2 s . co m*/ * * @param eml EmailOutModel */ public static void sendEmails(EmailOutModel eml) { SystemEmailModel account = null; String section = eml.getSection(); if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED") || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) { section = eml.getCaseType(); } //Get Account for (SystemEmailModel acc : Global.getSystemEmailParams()) { if (acc.getSection().equals(section)) { account = acc; break; } } //Account Exists? if (account != null) { //Case Location String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(eml) : FileService.getCaseFolderLocation(eml); //Attachment List boolean allFilesExists = true; List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId()); for (EmailOutAttachmentModel attach : attachmentList) { File attachment = new File(casePath + attach.getFileName()); boolean exists = attachment.exists(); if (exists == false) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("FileMissing"); item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } else { if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName())) || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) { if (!attachment.renameTo(attachment)) { allFilesExists = false; SECExceptionsModel item = new SECExceptionsModel(); item.setClassName("SendEmail"); item.setMethodName("sendEmails"); item.setExceptionType("File In Use"); item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId() + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator() + "File: " + attachment); ExceptionHandler.HandleNoException(item); break; } } } } if (allFilesExists) { //Set up Initial Merge Utility PDFMergerUtility ut = new PDFMergerUtility(); //List ConversionPDFs To Delete Later List<String> tempPDFList = new ArrayList<>(); //create email message body Date emailSentTime = new Date(); String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime); //Add Email Body To PDF Merge try { ut.addSource(casePath + emailPDFname); tempPDFList.add(casePath + emailPDFname); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //Get parts String FromAddress = account.getEmailAddress(); String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";")); String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";")); String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";")); String emailSubject = eml.getSubject(); String emailBody = eml.getBody(); //Set Email Parts Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailOutProperties(account); Session session = Session.getInstance(properties, auth); MimeMessage smessage = new MimeMessage(session); Multipart multipart = new MimeMultipart(); //Add Parts to Email Message try { smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) }); for (String To : TOAddressess) { if (EmailValidator.getInstance().isValid(To)) { smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To)); } } for (String CC : CCAddressess) { if (EmailValidator.getInstance().isValid(CC)) { smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC)); } } for (String BCC : BCCAddressess) { if (EmailValidator.getInstance().isValid(BCC)) { smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC)); } } smessage.setSubject(emailSubject); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailBody, "text/plain"); multipart.addBodyPart(messageBodyPart); //get attachments for (EmailOutAttachmentModel attachment : attachmentList) { String fileName = attachment.getFileName(); String extension = FilenameUtils.getExtension(fileName); //Convert attachments to PDF //If Image if (FileService.isImageFormat(fileName)) { fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Word Doc } else if (extension.equals("docx") || extension.equals("doc")) { fileName = WordToPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If Text File } else if ("txt".equals(extension)) { fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName); //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); tempPDFList.add(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } //If PDF } else if (FilenameUtils.getExtension(fileName).equals("pdf")) { //Add Attachment To PDF Merge try { ut.addSource(casePath + fileName); } catch (FileNotFoundException ex) { ExceptionHandler.Handle(ex); } } DataSource source = new FileDataSource(casePath + fileName); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } smessage.setContent(multipart); //Send Message if (Global.isOkToSendEmail()) { Transport.send(smessage); } else { Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject); } //DocumentFileName String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject()) .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf"; //Set Merge File Destination ut.setDestinationFileName(casePath + savedDoc); //Try to Merge try { ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } //Add emailBody Activity addEmailActivity(eml, savedDoc, emailSentTime); //Copy to related case folders if (section.equals("MED")) { List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml); if (relatedMedList.size() > 0) { for (RelatedCaseModel related : relatedMedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } else { //This is blanket and should grab all related cases. (UNTESTED outside of CMDS) List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml); if (relatedList.size() > 0) { for (EmailOutRelatedCaseModel related : relatedList) { //Copy finalized document to proper folder File srcFile = new File(casePath + savedDoc); File destPath = new File((section.equals("CSC") || section.equals("ORG")) ? FileService.getCaseFolderORGCSCLocation(related) : FileService.getCaseFolderLocationEmailOutRelatedCase(related)); destPath.mkdirs(); try { FileUtils.copyFileToDirectory(srcFile, destPath); } catch (IOException ex) { Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex); } //Add Related Case Activity Entry addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime); } } } //Clean SQL entries EmailOut.deleteEmailEntry(eml.getId()); EmailOutAttachment.deleteAttachmentsForEmail(eml.getId()); EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId()); //Clean up temp PDFs for (String tempPDF : tempPDFList) { new File(tempPDF).delete(); } } catch (AddressException ex) { ExceptionHandler.Handle(ex); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } } } }
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"); }//from w w w . jav a 2 s . c o m 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"); } }