Java Code Examples for javax.mail.MessagingException

The following are top voted examples for showing how to use javax.mail.MessagingException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: web-framework-for-java   File: MailHelper.java   View source code 10 votes vote down vote up
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);
}
 
Example 2
Project: ats-framework   File: MimePackage.java   View source code 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Project: ats-framework   File: MimePackage.java   View source code 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 4
Project: ats-framework   File: MimePackage.java   View source code 7 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: fake-smtp-server   File: EmailFactory.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 6
Project: REST-Web-Services   File: MailServiceImpl.java   View source code 6 votes vote down vote up
/**
 * {@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();
    }
}
 
Example 7
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 8
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
Project: ats-framework   File: Test_MailReportSender.java   View source code 6 votes vote down vote up
@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();
}
 
Example 10
Project: HueSense   File: MailService.java   View source code 6 votes vote down vote up
private void sendMail(String subject, String body, MailSettings settings) throws MessagingException {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", settings.getSmtpServer());
        props.put("mail.smtp.port", settings.getSmtpPort() + "");

        if (settings.getMode() == MailSettings.Mode.SSL) {
            props.put("mail.smtp.socketFactory.port", settings.getSmtpPort() + "");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
        } else if (settings.getMode() == MailSettings.Mode.TLS) {
            props.put("mail.smtp.starttls.enable", "true");
        }

        props.put("mail.smtp.auth", settings.isUseAuth() + "");

        Session session;
        if (settings.isUseAuth()) {
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getUser(), settings.getPass());
                }
            });
        } else {
            session = Session.getInstance(props);
        }

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settings.getFrom()));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(settings.getTo()));
        message.setSubject(subject);
        message.setText(body);

        Transport.send(message);

    }
 
Example 11
Project: solo-spring   File: MailService.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: tulingchat   File: MailUtil.java   View source code 6 votes vote down vote up
/**
 * 发送带附件的邮件
 */
@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);
	}
}
 
Example 13
Project: myfaces-trinidad   File: MessagesBackingBean.java   View source code 6 votes vote down vote up
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();
}
 
Example 14
Project: iotplatform   File: MailPlugin.java   View source code 6 votes vote down vote up
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);
}
 
Example 15
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Project: parabuild-ci   File: FolderTreeNode.java   View source code 6 votes vote down vote up
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();
}
   }
 
Example 17
Project: Spring-cloud-gather   File: EmailServiceImpl.java   View source code 6 votes vote down vote up
@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());
}
 
Example 18
Project: MailCopier   File: MailCopier.java   View source code 6 votes vote down vote up
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();
}
 
Example 19
Project: spring-rest-skeleton   File: LoggableMailSender.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 20
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 21
Project: myfaces-trinidad   File: FolderData.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: alfresco-repository   File: SubethaEmailMessage.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 23
Project: myfaces-trinidad   File: MessageData.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: trading4j   File: MailSender.java   View source code 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example 25
Project: alfresco-repository   File: AbstractMimeMessage.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 26
Project: jaffa-framework   File: EmailHelper.java   View source code 6 votes vote down vote up
/** Sends an email with an Excel spreadsheet as an attachment
 * @param smtpLocalhost (Optional) Name of host sending message, used in the HELO message for
 * server authentication
 * @param smtpUser (Optional) User name to authenticate to mail server. Not needed if server
 * is an 'open relay'
 * @param smtpPass (Optional) Password to authenticate to mail server. Not needed if server
 * is an 'open relay'
 * @param smtpHost (REQUIRED) name of mail server ie mail.yahoo.com
 * @param from (REQUIRED) from email ie [email protected]
 * @param to (REQUIRED) array of strings to send email to ie [email protected]
 * @param subject Text for the email subject (defaults to 'No Subject' if null)
 * @param bodyText Text for the main mail's body, in addition to the attachment
 * @param files Files to be attached to e-mail
 * @throws MessagingException Contains error if message could not be sent
 */
public static void emailFiles(String smtpHost, String smtpLocalhost, String smtpUser, String smtpPass, Boolean sendpartial, String from,
        String[] to, String subject, String bodyText, File[] files)
        throws MessagingException {
    BodyPart[] parts = null;
    if (files != null) {
        parts = new MimeBodyPart[files.length];
        
        // Create a part for each attachment
        for(int i=0;i<files.length; i++) {
            parts[i] = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(files[i]);
            parts[i].setDataHandler(new DataHandler(fileDataSource));
            parts[i].setFileName(fileDataSource.getName());
            parts[i].setDisposition(Part.ATTACHMENT);
        }
    }
    
    // Email it as an attachments
    EmailHelper.emailAttachments(smtpHost, smtpLocalhost, smtpUser, smtpPass, sendpartial, from,
            to, subject, bodyText, parts );
}
 
Example 27
Project: parabuild-ci   File: EmailNotificationManager.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: alfresco-repository   File: AbstractMimeMessage.java   View source code 5 votes vote down vote up
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();
}
 
Example 29
Project: QuizZz   File: MailHelper.java   View source code 5 votes vote down vote up
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;
}
 
Example 30
Project: lams   File: JavaMailSenderImpl.java   View source code 5 votes vote down vote up
@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);
	}
}
 
Example 31
Project: oscm   File: APPCommunicationServiceBeanTest.java   View source code 5 votes vote down vote up
@Test(expected = APPlatformException.class)
public void testComposeMessage_mailInitFails() throws Exception {
    // given
    MimeMessage mockMessage = mock(MimeMessage.class);
    doThrow(new MessagingException("Mail initialization fails")).when(
            mockMessage).setFrom(any(Address.class));
    doReturn(mockMessage).when(commService).getMimeMessage(
            any(Session.class));

    // when
    commService
            .composeMessage(Collections.singletonList("[email protected]"),
                    "subject", "text");
}
 
Example 32
Project: openpaas-mailets   File: GuessClassificationMailetTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 33
Project: openpaas-mailets   File: GuessClassificationMailet.java   View source code 5 votes vote down vote up
@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();
}
 
Example 34
Project: openpaas-mailets   File: ClassificationRequestBody.java   View source code 5 votes vote down vote up
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()));
}
 
Example 35
Project: REST-Web-Services   File: MailServiceImpl.java   View source code 5 votes vote down vote up
/**
 * {@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();
    }
}
 
Example 36
Project: lams   File: MimeMailMessage.java   View source code 5 votes vote down vote up
@Override
public void setBcc(String bcc) throws MailParseException {
	try {
		this.helper.setBcc(bcc);
	}
	catch (MessagingException ex) {
		throw new MailParseException(ex);
	}
}
 
Example 37
Project: sunbird-utils   File: EmailTest.java   View source code 5 votes vote down vote up
@Test
public void sendEmailWithAttachmentTest() throws MessagingException {
  String subject = "Test1";
  VelocityContext context = new VelocityContext();
  context.put(JsonKey.NAME, "Manzarul");
  SendMail.sendAttachment(new String[] {"[email protected]"}, "test email",subject,
      "emailtemplate.vm");
  List<Message> inbox = Mailbox.get("[email protected]");
  Assert.assertTrue(inbox.size() >0 );
  Assert.assertEquals(subject, inbox.get(0).getSubject());
}
 
Example 38
Project: Hotel-Properties-Management-System   File: SendEmailToUser.java   View source code 5 votes vote down vote up
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());
	}
}
 
Example 39
Project: Mastering-Java-EE-Development-with-WildFly   File: SendMail.java   View source code 5 votes vote down vote up
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);
}
 
Example 40
Project: alfresco-repository   File: EMLTransformer.java   View source code 5 votes vote down vote up
/**
 * 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();
    }
}