/** * Reconnects if connection is closed. * <b>Note</b>Internal method * @return true if store re-connection is performed and this means that close should be closed after the work is done * @throws MessagingException */ public boolean reconnectStoreIfClosed() throws MessagingException { boolean storeReconnected = false; // the folder is empty when the message is not loaded from IMAP server, but from a file Folder imapFolder = message.getFolder(); if (imapFolder == null) { imapFolder = this.partOfImapFolder; } else { partOfImapFolder = imapFolder; // keep reference } if (imapFolder != null) { Store store = imapFolder.getStore(); if (store != null) { if (!store.isConnected()) { log.debug("Reconnecting store... "); store.connect(); storeReconnected = true; } // Open folder in read-only mode if (!imapFolder.isOpen()) { log.debug("Reopening folder " + imapFolder.getFullName() + " in order to get contents of mail message"); imapFolder.open(Folder.READ_ONLY); } } } return storeReconnected; }
public Email convert(RawData rawData) throws IOException { try { Session s = Session.getDefaultInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(s, rawData.getContentAsStream()); String subject = Objects.toString(mimeMessage.getSubject(), UNDEFINED); ContentType contentType = ContentType.fromString(mimeMessage.getContentType()); Object messageContent = mimeMessage.getContent(); switch (contentType) { case HTML: case PLAIN: return buildPlainOrHtmlEmail(rawData, subject, contentType, messageContent); case MULTIPART_ALTERNATIVE: return buildMultipartAlternativeMail(rawData, subject, (Multipart) messageContent); default: throw new IllegalStateException("Unsupported e-mail content type " + contentType.name()); } } catch (MessagingException e) { return buildFallbackEmail(rawData); } }
public static void sendMail(String host, int port, String username, String password, String recipients, String subject, String content, String from) throws AddressException, MessagingException { 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", port); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); message.setSubject(subject); message.setText(content); Transport.send(message); }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithNewPassword( @NotBlank @Email final String email, @NotBlank final String newPassword ) { log.info("Called with e-mail {}, newPassword {}", email, newPassword); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Recover password"); helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
/** * Get the attachment content type * * @param partIndex * @return * @throws PackageException */ @PublicAtsApi public String getAttachmentContentType( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= attachmentPartIndices.size()) { throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'"); } try { MimePart part = getPart(attachmentPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getBaseType(); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Add an attachment with the specified content - the attachment will have a * content type text\plain and the specified character set * * @param content * the content of the attachment * @param charset * the character set * @param fileName * the file name for the content-disposition header * @throws PackageException * on error */ @PublicAtsApi public void addAttachment( String content, String charset, String fileName ) throws PackageException { try { // add attachment to multipart content MimeBodyPart attPart = new MimeBodyPart(); attPart.setText(content, charset, PART_TYPE_TEXT_PLAIN); attPart.setDisposition(MimeBodyPart.ATTACHMENT); attPart.setFileName(fileName); addPart(attPart, PART_POSITION_LAST); } catch (MessagingException me) { throw new PackageException(me); } }
@Test( expected = MailReportSendException.class) public void emptyAddressBcc() throws MessagingException { expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator); expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost"); expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25"); expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[0]); expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]); expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[]{ "" }); expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom"); replayAll(); triggerRun(); verifyAll(); }
/** * Transport recipients to InternetAddress array. * * @param recipients * the set of all recipients * @return InternetAddress array of all recipients internetAddress * @throws MessagingException * messagingException from javax.mail */ private InternetAddress[] transformRecipients(final Set<String> recipients) throws MessagingException { if (recipients.isEmpty()) { throw new MessagingException("recipients of mail should not be empty"); } final InternetAddress[] ret = new InternetAddress[recipients.size()]; int i = 0; for (String recipient : recipients) { ret[i] = new InternetAddress(recipient); i++; } return ret; }
/** * 发送带附件的邮件 */ @Async("mailAsync") public void sendAttachmentsMail(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } }
public String compact() throws MessagingException { Folder folder = _folderData.getFolder(); folder.open(Folder.READ_WRITE); // It would be much more efficient to simply trim out // the list of "expunged" messages from the data model; // instead, we're refreshing the list. folder.expunge(); folder.close(true); return refresh(); }
private void sendMail(SendMailActionMsg msg) throws MessagingException { log.debug("Sending mail {}", msg); MimeMessage mailMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mailMsg, "UTF-8"); helper.setFrom(msg.getFrom()); helper.setTo(msg.getTo()); if (!StringUtils.isEmpty(msg.getCc())) { helper.setCc(msg.getCc()); } if (!StringUtils.isEmpty(msg.getBcc())) { helper.setBcc(msg.getBcc()); } helper.setSubject(msg.getSubject()); helper.setText(msg.getBody()); mailSender.send(helper.getMimeMessage()); log.debug("Mail sent {}", msg); }
/** * Get the recipients of the specified type * * @param recipientType * the type of recipient - to, cc or bcc * @return array with recipients, emtpy array of no recipients of this type * are present * @throws PackageException */ @PublicAtsApi public String[] getRecipients( RecipientType recipientType ) throws PackageException { try { Address[] recipientAddresses = message.getRecipients(recipientType.toJavamailType()); // return an empty string if no recipients are present if (recipientAddresses == null) { return new String[]{}; } String[] recipients = new String[recipientAddresses.length]; for (int i = 0; i < recipientAddresses.length; i++) { recipients[i] = recipientAddresses[i].toString(); } return recipients; } catch (MessagingException me) { throw new PackageException(me); } }
/** * Get the character set of a regular part * * @param partIndex * the index of the part * @return the charset * @throws PackageException */ @PublicAtsApi public String getRegularPartCharset( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= regularPartIndices.size()) { throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'"); } try { MimePart part = getPart(regularPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getParameter("charset"); } catch (MessagingException me) { throw new PackageException(me); } }
protected void loadChildren() { // if it is a leaf, just say we have loaded them if (isLeaf()) { hasLoaded = true; return; } try { // Folder[] sub = folder.listSubscribed(); Folder[] sub = folder.list(); // add a FolderTreeNode for each Folder int num = sub.length; for(int i = 0; i < num; i++) { FolderTreeNode node = new FolderTreeNode(sub[i]); // we used insert here, since add() would make // another recursive call to getChildCount(); insert(node, i); } } catch (MessagingException me) { me.printStackTrace(); } }
@Override public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException { final String subject = env.getProperty(type.getSubject()); final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName()); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipient.getEmail()); helper.setSubject(subject); helper.setText(text); if (StringUtils.hasLength(attachment)) { helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes())); } mailSender.send(message); log.info("{} email notification has been send to {}", type, recipient.getEmail()); }
public synchronized void sendNext() throws MessagingException, IOException { if(files.isEmpty()) { throw new RuntimeException("The Queue is empty."); } File file = files.peek(); String path = file.getPath(); String name = file.getName(); if(transport == null || !transport.isConnected()) { senderConnect(); } String[] to = pManager.get_To().split(","); sendMultipartMessage(name, to, "", path); files.pop(); filesStr.pop(); if(files.isEmpty()) { // copy finalized set_fPointer(0); notifySendCopyListeners(); } else { set_fPointer(fPointer + 1); } notifyFilesListeners(); }
/** * Extracts string data from {@link MimeMessage}. * * @param mimeMessage * @return */ public static String getStringInfo(MimeMessage mimeMessage) { StringBuilder sb = new StringBuilder("MimeMessage: "); try { sb.append("from=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getFrom())).append("; "); sb.append("replyTo=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getReplyTo())).append("; "); sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.TO))).append("; "); sb.append("cc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.CC))).append("; "); sb.append("bcc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.BCC))).append("; "); sb.append("subject=").append(mimeMessage.getSubject()); } catch (MessagingException e) { LOG.error("Error retrieving log message: {}", e.getMessage()); } return sb.toString(); }
/** * Get the content type of a regular part * * @param partIndex * the index of the regular part * @return the content type as string * @throws PackageException */ @PublicAtsApi public String getRegularPartContentType( int partIndex ) throws PackageException { // first check if there is part at this position at all if (partIndex >= regularPartIndices.size()) { throw new NoSuchMimePartException("No regular part at position '" + partIndex + "'"); } try { MimePart part = getPart(regularPartIndices.get(partIndex)); // get the content type header ContentType contentType = new ContentType(part.getContentType()); return contentType.getBaseType(); } catch (MessagingException me) { throw new PackageException(me); } }
/** * converts {@link Folder}s to {@link FolderData}s. */ public static FolderData[] toFolderData(AccountData data, Folder[] folders) throws MessagingException { int sz = folders.length; if (sz > 0) { FolderData[] subs = new FolderData[sz]; for(int i=0; i<sz; i++) { Folder f = folders[i]; subs[i] = new FolderData(data, f); } return subs; } return null; }
/** * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter. * * @param defaultPrefix This prefix fill be used for generating file name. * @param messagePart A part of message * @return File name. * @throws MessagingException */ private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException { String fileName = messagePart.getFileName(); if (fileName != null) { try { fileName = MimeUtility.decodeText(fileName); } catch (UnsupportedEncodingException ex) { // Nothing to do :) } } else { fileName = defaultPrefix; if (messagePart.isMimeType(MIME_PLAIN_TEXT)) fileName += ".txt"; else if (messagePart.isMimeType(MIME_HTML_TEXT)) fileName += ".html"; else if (messagePart.isMimeType(MIME_XML_TEXT)) fileName += ".xml"; else if (messagePart.isMimeType(MIME_IMAGE)) fileName += ".gif"; } return fileName; }
/** * Get the number of lines in the message. If the original message is a * more complex type like multipart, this method will actually search * through all the parts and try and find a text/plain or text/html * and getLineCount() will return the number of messages in that part. */ public int getLineCount() throws MessagingException { // catch IOExceptions and ignore them, because content type really // shouldn't care much about io exceptions try { _tryInit(); } catch (IOException ioe) { ; } return _lineCount; }
/** * Sends an email. * * @param from * The Email-address from the sender of this mail. * @param to * The Email-address of the receiver of this mail. * @param subject * The subject of the mail. * @param body * The content of the mail. * @throws MailSendingException * When sending the mail failed. */ public void sendMail(final String from, final String to, final String subject, final String body) throws MailSendingException { final MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSentDate(new Date()); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (final MessagingException e) { throw new MailSendingException("Sending an email failed.", e); } }
private void setPersistedHeaders() throws MessagingException { NodeService nodeService = serviceRegistry.getNodeService(); if (nodeService.hasAspect(messageFileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_MESSAGE_HEADERS)) { @SuppressWarnings("unchecked") List<String> messageHeaders = (List<String>)nodeService.getProperty(messageFileInfo.getNodeRef(), ImapModel.PROP_MESSAGE_HEADERS); if (messageHeaders == null) { return; } for (String header : messageHeaders) { String headerValue = header.substring(header.indexOf(ImapModel.MESSAGE_HEADER_TO_PERSIST_SPLITTER) + 1); String headerName = header.substring(0, header.indexOf(ImapModel.MESSAGE_HEADER_TO_PERSIST_SPLITTER)); setHeader(headerName, headerValue); } } }
/** * This method resturns only the email address portion of the sender * contained in the first From header * * @return the sender address * @throws PackageException */ @PublicAtsApi public String getSenderAddress() throws PackageException { try { Address[] fromAddresses = message.getFrom(); if (fromAddresses == null || fromAddresses.length == 0) { throw new PackageException("Sender not present"); } InternetAddress fromAddress = (InternetAddress) fromAddresses[0]; return fromAddress.getAddress(); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Sends message to the list of recipients and BCC list */ private void sendMessage(final EmailRecipients recipients, final StringBuffer messageSubject, final StringBuffer messageBody, final byte priorityCode) throws MessagingException { // grab *all* system props final List systemProperties = SystemConfigurationManagerFactory.getManager().getSystemProperties(); // sendMessage will figure out which ones to use final InternetAddress senderAddress = NotificationUtils.getSystemAdminAddress(); sendMessage(systemProperties, senderAddress, recipients, messageSubject, messageBody, priorityCode); }
protected void setMessageHeaders() throws MessagingException { setHeader(MIME_VERSION, "1.0"); // Optional headers for further implementation of multiple Alfresco server support. setHeader(X_ALF_NODEREF_ID, messageFileInfo.getNodeRef().getId()); // setHeader(X_ALF_SERVER_UID, imapService.getAlfrescoServerUID()); setPersistedHeaders(); }
public static String extractUrlFromMail(Message message) throws IOException, MessagingException { String body = (String) message.getContent(); Pattern pattern = Pattern.compile(".*http://localhost:8080(.*)((\r\n)|(\n)).*"); Matcher matcher = pattern.matcher(body); if (matcher.find()) { return matcher.group(1); } return null; }
@Override public MimeMessage createMimeMessage(InputStream contentStream) throws MailException { try { return new MimeMessage(getSession(), contentStream); } catch (MessagingException ex) { throw new MailParseException("Could not parse raw MIME content", ex); } }
@Test public void initShouldThrowWhenTimeOutInMsIsNegative() throws Exception { expectedException.expect(MessagingException.class); FakeMailetConfig config = FakeMailetConfig.builder() .setProperty("serviceUrl", "my url") .setProperty(TIMEOUT_IN_MS, "-1") .build(); GuessClassificationMailet testee = new GuessClassificationMailet(); testee.init(config); }
@Override public void init() throws MessagingException { LOGGER.debug("init GuessClassificationMailet"); timeoutInMs = parseTimeout(); serviceUrl = getInitParameter(SERVICE_URL); if (LOGGER.isDebugEnabled()) { LOGGER.debug("serviceUrl value: " + serviceUrl); } if (Strings.isNullOrEmpty(serviceUrl)) { throw new MailetException("'serviceUrl' is mandatory"); } serviceUsername = getInitParameter(SERVICE_USERNAME); if (LOGGER.isDebugEnabled()) { LOGGER.debug("serviceUsername value: " + serviceUsername); } if (Strings.isNullOrEmpty(serviceUsername)) { throw new MailetException("'serviceUsername' is mandatory"); } servicePassword = getInitParameter(SERVICE_PASSWORD); if (Strings.isNullOrEmpty(servicePassword)) { throw new MailetException("'servicePassword' is mandatory"); } headerName = getInitParameter(HEADER_NAME, HEADER_NAME_DEFAULT_VALUE); if (LOGGER.isDebugEnabled()) { LOGGER.debug("headerName value: " + headerName); } if (Strings.isNullOrEmpty(headerName)) { throw new MailetException("'headerName' is mandatory"); } executor = createHttpExecutor(); }
public static ClassificationRequestBody from(Mail mail, UUID messageId) throws MessagingException, IOException { MimeMessage message = mail.getMessage(); return new ClassificationRequestBody(messageId, Emailers.from(message.getFrom()), Recipients.from(message), ImmutableList.of(Optional.ofNullable(message.getSubject()).orElse("")), retrieveTextPart(mail), Optional.ofNullable(message.getSentDate()).map(x -> x.toInstant())); }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithEmailChangeToken( @NotBlank @Email final String email, @NotBlank final String token ) { log.info("Called with e-mail {}, token {}", email, token); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Change e-mail"); helper.setText("Change e-mail address, click the link below:<br />" + "<a href='" + "https://localhost:8443" + "/settings/changeEmail/thanks?token=" + token + "'>" + "Click here to complete the change of your e-mail" + "</a>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
@Override public void setBcc(String bcc) throws MailParseException { try { this.helper.setBcc(bcc); } catch (MessagingException ex) { throw new MailParseException(ex); } }
public void setFrom(String from, String to) { try { message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); } catch (MessagingException e) { loggingEngine.setMessage("Email sending error : " + e.getMessage()); } }
public void completeLocalClientSend(String... credentials) throws AddressException, MessagingException { mailServerProperties = getProperties(); mailServerProperties.put("mail.smtp.port", "25000"); mailServerProperties.put("mail.smtp.auth", "false"); mailServerProperties.put("mail.smtp.starttls.enable", "false"); completeClientSend("localhost", credentials); }
/** * Finds text on a given mail part. Accepted parts types are text/html and text/plain. * Attachments are ignored * * @param part * @param sb * @throws IOException * @throws MessagingException */ private void processPart(Part part, StringBuilder sb) throws IOException, MessagingException { boolean isAttachment = Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()); if (isAttachment) { return; } if (part.getContentType().contains(MimetypeMap.MIMETYPE_TEXT_PLAIN)) { sb.append(part.getContent().toString()); } else if (part.getContentType().contains(MimetypeMap.MIMETYPE_HTML)) { String mailPartContent = part.getContent().toString(); //create a temporary html file with same mail part content and encoding File tempHtmlFile = TempFileProvider.createTempFile("EMLTransformer_", ".html"); ContentWriter contentWriter = new FileContentWriter(tempHtmlFile); contentWriter.setEncoding(getMailPartContentEncoding(part)); contentWriter.setMimetype(MimetypeMap.MIMETYPE_HTML); contentWriter.putContent(mailPartContent); //transform html file's content to plain text EncodingAwareStringBean extractor = new EncodingAwareStringBean(); extractor.setCollapse(false); extractor.setLinks(false); extractor.setReplaceNonBreakingSpaces(false); extractor.setURL(tempHtmlFile, contentWriter.getEncoding()); sb.append(extractor.getStrings()); tempHtmlFile.delete(); } }
@Test @RunAsClient public void send() throws AddressException, MessagingException { SendMail sendMail = new SendMail(); sendMail.completeGoogleClientSend(); logger.info("\n\n ===> Your Java Program has just sent an Email successfully. Check your email.."); sendMail.completeLocalClientSend("", ""); logger.info("\n\n ===> Your Java Program has just sent an Email successfully. Check your email.."); assertTrue("message received", myFactory.getBody().contains("Test email by Vige.it JavaMail API example")); }