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   Source Code and License 12 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   Source Code and License 8 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 3
Project: ats-framework   File: MimePackage.java   Source Code and License 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 4
Project: alfresco-repository   File: SubethaEmailMessage.java   Source Code and License 7 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 5
Project: ats-framework   File: MimePackage.java   Source Code and License 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 6
Project: fake-smtp-server   File: EmailFactory.java   Source Code and License 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 7
Project: REST-Web-Services   File: MailServiceImpl.java   Source Code and License 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 8
Project: ats-framework   File: MimePackage.java   Source Code and License 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 9
Project: ats-framework   File: MimePackage.java   Source Code and License 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 10
Project: ats-framework   File: Test_MailReportSender.java   Source Code and License 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 11
Project: HueSense   File: MailService.java   Source Code and License 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 12
Project: solo-spring   File: MailService.java   Source Code and License 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 13
Project: tulingchat   File: MailUtil.java   Source Code and License 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 14
Project: AndroidKillerService   File: SimpleMailSender.java   Source Code and License 6 votes vote down vote up
public boolean sendHtmlMail(MailSenderInfo mailInfo) {
    XLog.d("发送网页版邮件!");
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        String[] receivers = mailInfo.getReceivers();
        Address[] tos = new InternetAddress[receivers.length];
        for (int i = 0; i < receivers.length; i++) {
            tos[i] = new InternetAddress(receivers[i]);
        }
        mailMessage.setRecipients(Message.RecipientType.TO, tos);
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());

        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
Example 15
Project: myfaces-trinidad   File: MessagesBackingBean.java   Source Code and License 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 16
Project: Spring-web-shop-project   File: SendEmailUserAccount.java   Source Code and License 6 votes vote down vote up
public static void sendEmailWithOrder(String text, String eMail, HttpServletRequest request) {
    try {
        Session session = EmailActions.authorizeWebShopEmail();

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMail, false));
        msg.setSubject("Shop order");
        msg.setText(text);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        System.out.println("Error : " + e);
    }
}
 
Example 17
Project: iotplatform   File: MailPlugin.java   Source Code and License 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 18
Project: ats-framework   File: MimePackage.java   Source Code and License 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 19
Project: parabuild-ci   File: FolderTreeNode.java   Source Code and License 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 20
Project: Spring-cloud-gather   File: EmailServiceImpl.java   Source Code and License 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 21
Project: MailCopier   File: MailCopier.java   Source Code and License 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 22
Project: spring-rest-skeleton   File: LoggableMailSender.java   Source Code and License 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 23
Project: ats-framework   File: MimePackage.java   Source Code and License 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 24
Project: myfaces-trinidad   File: FolderData.java   Source Code and License 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 25
Project: myfaces-trinidad   File: MessageData.java   Source Code and License 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 26
Project: trading4j   File: MailSender.java   Source Code and License 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 27
Project: alfresco-repository   File: AbstractMimeMessage.java   Source Code and License 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 28
Project: jaffa-framework   File: EmailHelper.java   Source Code and License 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 29
Project: parabuild-ci   File: EmailNotificationManager.java   Source Code and License 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 30
Project: alfresco-repository   File: AbstractMimeMessage.java   Source Code and License 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 31
Project: QuizZz   File: MailHelper.java   Source Code and License 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 32
Project: lams   File: JavaMailSenderImpl.java   Source Code and License 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 33
Project: oscm   File: APPCommunicationServiceBeanTest.java   Source Code and License 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 34
Project: openpaas-mailets   File: GuessClassificationMailetTest.java   Source Code and License 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 35
Project: openpaas-mailets   File: GuessClassificationMailet.java   Source Code and License 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 36
Project: openpaas-mailets   File: ClassificationRequestBody.java   Source Code and License 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 37
Project: REST-Web-Services   File: MailServiceImpl.java   Source Code and License 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 38
Project: lams   File: MimeMailMessage.java   Source Code and License 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 39
Project: sunbird-utils   File: EmailTest.java   Source Code and License 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 40
Project: Hotel-Properties-Management-System   File: SendEmailToUser.java   Source Code and License 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 41
Project: Mastering-Java-EE-Development-with-WildFly   File: SendMail.java   Source Code and License 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 42
Project: alfresco-repository   File: EMLTransformer.java   Source Code and License 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();
    }
}
 
Example 43
Project: Mastering-Java-EE-Development-with-WildFly   File: SendMailTestCase.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 44
Project: alfresco-repository   File: RuleServiceCoverageTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test:
 *          rule type:  inbound
 *          condition:  no-condition
 *          action:     mail  
 * @throws MessagingException 
 * @throws IOException 
 */
public void testMailAction() throws MessagingException, IOException
{
    this.nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null);
    
    Map<String, Serializable> params = new HashMap<String, Serializable>(1);
    params.put(MailActionExecuter.PARAM_TO, "[email protected]");
    params.put(MailActionExecuter.PARAM_SUBJECT, "Unit test");
    params.put(MailActionExecuter.PARAM_TEXT, "This is a test to check that the mail action is working.");
    
    Rule rule = createRule(
    		RuleType.INBOUND, 
    		MailActionExecuter.NAME, 
    		params, 
    		NoConditionEvaluator.NAME, 
    		null);
    
    this.ruleService.saveRule(this.nodeRef, rule);

    MailActionExecuter mailService = (MailActionExecuter) ((ApplicationContextFactory) applicationContext
                .getBean("OutboundSMTP")).getApplicationContext().getBean("mail");
    mailService.setTestMode(true);
    mailService.clearLastTestMessage();
    
    this.nodeService.createNode(
            this.nodeRef,
            ContentModel.ASSOC_CHILDREN,                
            QName.createQName(TEST_NAMESPACE, "children"),
            ContentModel.TYPE_CONTENT,
            getContentProperties()).getChildRef();        
    
    // An email should appear in the recipients email
    // System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef));
    MimeMessage lastMessage = mailService.retrieveLastTestMessage();
    assertNotNull("Message should have been sent", lastMessage);
    System.out.println("Sent email with subject: " + lastMessage.getSubject());
    System.out.println("Sent email with content: " + lastMessage.getContent());
}
 
Example 45
Project: c4sg-services   File: EmailServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendVolunteerApplicationEmail() throws MessagingException {
	
	List<String> skills = Arrays.asList("Tester", "Coder", "Cop");
	
	User user = new User();
	user.setEmail("[email protected]");
	user.setFirstName("Rowland");
	user.setLastName("Ogwara");
	user.setTitle("Coolio Developer");
	user.setChatUsername("rogwara");
	user.setIntroduction("Something very interesting about this person");
	
	Project project = new Project();
	project.setName("Test Project");
	
	Map<String, Object> mailContext = new HashMap<String, Object>();
   	mailContext.put("user", user);
   	mailContext.put("skills", skills);
   	mailContext.put("project", project);
   	mailContext.put("message", message);
   	
   	mailService.sendWithContext(from, user.getEmail(), "", "Test Email", "volunteer-application", mailContext);
   	
   	// received message
   	MimeMessage[] receivedMessages = mailer.getReceivedMessages();
       assertEquals(1, receivedMessages.length);
       
       MimeMessage msg = receivedMessages[0];
       
       assertThat(from, is(msg.getFrom()[0].toString()));
       assertThat("Test Email", is(msg.getSubject()));
}
 
Example 46
Project: reactive-components   File: TestMail.java   Source Code and License 5 votes vote down vote up
private MimeMessage createMessage(Session session, String body) {
    try {
        MimeMessage mesage = new MimeMessage(session);
        mesage.setSubject("Test Mail");
        mesage.setText(body);
        return mesage;
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 47
Project: matrix-appservice-email   File: EmailFormatterOutboud.java   Source Code and License 5 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, List<_BridgeMessageContent> contents, boolean allowReply) throws MessagingException, IOException {
    MimeMultipart body = new MimeMultipart();
    body.setSubType("alternative");

    for (_BridgeMessageContent content : contents) {
        MimeMultipart contentBody = new MimeMultipart();
        contentBody.setSubType("related");

        Optional<_EmailTemplateContent> contentTemplateOpt = template.getContent(content.getMime());
        if (!contentTemplateOpt.isPresent()) {
            continue;
        }

        _EmailTemplateContent contentTemplate = contentTemplateOpt.get();
        contentBody.addBodyPart(makeBodyPart(data, contentTemplate, content));

        if (contentTemplate.getContent().contains(EmailTemplateToken.SenderAvatar.getToken()) &&
                data.getSenderAvatar() != null && data.getSenderAvatar().isValid()) {
            log.info("Adding avatar for sender");

            MimeBodyPart avatarBp = new MimeBodyPart();
            _MatrixContent avatar = data.getSenderAvatar();
            String filename = avatar.getFilename().orElse("unknown." + avatar.getType().replace("image/", ""));

            avatarBp.setContent(avatar.getData(), avatar.getType());
            avatarBp.setContentID("<" + senderAvatarId + ">");
            avatarBp.setDisposition("inline; filename=" + filename + "; size=" + avatar.getData().length + ";");

            contentBody.addBodyPart(avatarBp);
        }

        MimeBodyPart part = new MimeBodyPart();
        part.setContent(contentBody);

        body.addBodyPart(part);
    }

    return makeEmail(data, template, body, allowReply);
}
 
Example 48
Project: lams   File: MimeMessageHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Add an attachment to the MimeMessage, taking the content from a
 * {@code javax.activation.DataSource}.
 * <p>Note that the InputStream returned by the DataSource implementation
 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
 * {@code getInputStream()} multiple times.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail (the content type will be determined by this)
 * @param dataSource the {@code javax.activation.DataSource} to take
 * the content from, determining the InputStream and the content type
 * @throws MessagingException in case of errors
 * @see #addAttachment(String, org.springframework.core.io.InputStreamSource)
 * @see #addAttachment(String, java.io.File)
 */
public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
	Assert.notNull(attachmentFilename, "Attachment filename must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
		mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
		mimeBodyPart.setDataHandler(new DataHandler(dataSource));
		getRootMimeMultipart().addBodyPart(mimeBodyPart);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to encode attachment filename", ex);
	}
}
 
Example 49
Project: alfresco-repository   File: AbstractMailActionExecuterTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test for MNT-11079
 */
@Test
public void testSendingToUserWithMailAlikeName() throws IOException, MessagingException
{
    final String USER_1 = "[email protected]";
    final String USER_1_EMAIL = "[email protected]";

    try
    {
        createUser(USER_1, USER_1_EMAIL);

        Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, USER_1);

        mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");

        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());

        ACTION_SERVICE.executeAction(mailAction, null);

        MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
        Assert.assertNotNull(message);
        Assert.assertEquals("Hello Jan 1, 1970", (String) message.getContent());
        Assert.assertEquals(1, message.getAllRecipients().length);
        javax.mail.internet.InternetAddress address = (InternetAddress) message.getAllRecipients()[0];
        Assert.assertEquals(USER_1_EMAIL, address.getAddress());
    }
    finally
    {
        // tidy up
        PERSON_SERVICE.deletePerson(USER_1);
    }
}
 
Example 50
Project: leoapp-sources   File: MailClient.java   Source Code and License 5 votes vote down vote up
/**
 * Bereitet den Mailinhalt zum Senden vor.
 *
 * @throws MessagingException -
 * @throws UnsupportedEncodingException -
 */
public void createEmailMessage() throws MessagingException, UnsupportedEncodingException {
    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }
    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");
}
 
Example 51
Project: mongodb-rdbms-sync   File: Mailer.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static Multipart readEmailFromHtml(String filePath, Multipart multipart, SyncEvent event, Exception ex,
		String mailType) {
	BodyPart messageBodyPart = new MimeBodyPart();
	String msg = readContentFromFile(filePath);
	try {
		// Set key values
		Map<String, String> input = new HashMap<String, String>();
		input.put(SyncAttrs.EVENT_NAME, event.getEventName());
		input.put(SyncAttrs.EVENT_ID, event.getEventId().toString());
		input.put(SyncAttrs.MAP_NAME, event.getMapName());
		input.put(SyncAttrs.MAP_ID, event.getMapId().toString());
		input.put(SyncAttrs.EVENT_TYPE, event.getEventType().toString());
		input.put(SyncAttrs.HOST_NAME, getHostName());
		if (mailType.equalsIgnoreCase(FAILURE)) {
			input.put(SyncAttrs.TRACE, ExceptionUtils.getStackTrace(ex));
		} else if (mailType.equalsIgnoreCase(STARTED)) {
			input.put(SyncAttrs.START_TIME, new Date(System.currentTimeMillis()).toString());
		} else if(mailType.equalsIgnoreCase(COMPLETED)){
			if(event.getMarker()!=null){
				input.put(SyncAttrs.ROWS_READ, Integer.toString(event.getMarker().getRowsDumped()));
				input.put(SyncAttrs.ROWS_DUMPED, Integer.toString(event.getMarker().getRowsDumped()));
				input.put(SyncAttrs.TOTAL_ROWS, Integer.toString(event.getMarker().getTotalRows()));
				input.put(SyncAttrs.START_TIME, event.getMarker().getStartTime().toString());
				input.put(SyncAttrs.END_TIME, event.getMarker().getEndTime().toString());
				input.put(SyncAttrs.DURATION,
						formatDate(event.getMarker().getStartTime(), event.getMarker().getEndTime()));
			}
		}
		input.put("DATE", new Date().toString());
		Set<Entry<String, String>> entries = input.entrySet();
		for (Map.Entry<String, String> entry : entries) {
			msg = msg.replace(entry.getKey().trim(), entry.getValue() !=null ? entry.getValue().trim() : "-");
		}
	} catch (Exception exception) {
		logger.info("Exception While Setting The Values For Html Fields "+exception);
		exception.printStackTrace();
	}
	try {
		messageBodyPart.setContent(msg, "text/html");
		multipart.addBodyPart(messageBodyPart);
	} catch (MessagingException e) {
		logger.info("Exception While Setting Message Body "+e);
	}
	return multipart;
}
 
Example 52
Project: Java_Good   File: MailHelper.java   Source Code and License 5 votes vote down vote up
public List<MailMessage> waitForMail(int count, long timeout) throws MessagingException, IOException{
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() < start + timeout) {
        if (wiser.getMessages().size() >= count) {
            return wiser.getMessages().stream().map((m) -> toModelMail(m)).collect(Collectors.toList());
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    throw new Error("No mail : (");
}
 
Example 53
Project: myfaces-trinidad   File: MessageDataModel.java   Source Code and License 5 votes vote down vote up
@Override
public void setWrappedData(Object data)
{
  Folder newFolder = (Folder) data;
  _folder = newFolder;
  _rowIndex = -1;

  if (newFolder != null)
  {
    try
    {
      _count = _folder.getMessageCount();
    }
    // Need to handle more cleanly
    catch (MessagingException me)
    {
      _count = 0;
      _LOG.log(Level.SEVERE, "Could not get message count",  me);
    }
  }
  else
  {
    _count = 0;
  }

  _loaded = new MessageData[_count];
}
 
Example 54
Project: CustomAndroidOneSheeld   File: EmailShield.java   Source Code and License 5 votes vote down vote up
public static Message createMessageWithEmail(MimeMessage email)
        throws MessagingException, IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    email.writeTo(bytes);
    String encodedEmail = Base64.encodeToString(bytes.toByteArray(), Base64.URL_SAFE);
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example 55
Project: oscm   File: MailReader.java   Source Code and License 5 votes vote down vote up
/**
 * Get the content of the last message with the given subject.
 *
 * @param subject
 *            the subject
 * @return the content of the last message with the given subject
 */
public String getLastMailContentWithSubject(String subject)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String content = null;
    while (retries < 40) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                content = getMessageContent(message);
            }
        }
        folder.close(true);

        if (content != null) {
            return content;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return "";
}
 
Example 56
Project: plugin-password   File: PasswordResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void requestRecovery() throws MessagingException {
	final PasswordResource resource = newResource();
	final MimeMessage message = Mockito.mock(MimeMessage.class);
	resource.repository = repository;
	resource.iamProvider = new IamProvider[] { iamProvider };
	Mockito.when(resource.configurationResource.get("password.mail.url")).thenReturn("host");
	final MailServicePlugin mailServicePlugin = resource.servicePluginLocator.getResource("service:mail:smtp:local",
			MailServicePlugin.class);
	Mockito.when(mailServicePlugin.send(ArgumentMatchers.eq("service:mail:smtp:local"),
			ArgumentMatchers.any(MimeMessagePreparator.class))).thenAnswer(

					i -> {
						MimeMessagePreparator mimeMessagePreparator = (MimeMessagePreparator) i.getArguments()[1];
						try {
							mimeMessagePreparator.prepare(message);
						} catch (final Exception e) {
							exOnPrepare = e;
						}
						return mimeMessagePreparator;
					});
	resource.requestRecovery("fdaugan", "[email protected]");
	em.flush();

	Assert.assertNull(exOnPrepare);
	final List<PasswordReset> requests = repository.findAll();
	Assert.assertEquals(1, requests.size());
	final PasswordReset passwordReset = requests.get(0);
	Assert.assertEquals("fdaugan", passwordReset.getLogin());

	Mockito.verify(message, Mockito.atLeastOnce())
			.setContent("First Last-<a href=\"host#reset=" + passwordReset.getToken() + "/fdaugan\">host#reset="
					+ passwordReset.getToken() + "/fdaugan</a>-First Last-<a href=\"host#reset="
					+ passwordReset.getToken() + "/fdaugan\">host#reset=" + passwordReset.getToken()
					+ "/fdaugan</a>", "text/html; charset=UTF-8");
}
 
Example 57
Project: pathological-reports   File: EmailService.java   Source Code and License 5 votes vote down vote up
public void send(String email, String token) throws EmailException {
	Properties properties = System.getProperties();

	properties.put("mail.smtp.auth", "true");
	properties.put("mail.smtp.starttls.enable", "true");
	properties.put("mail.smtp.host", emailProperties.getSmtpHost());
	properties.put("mail.smtp.port", emailProperties.getSmtpPort());

	Session session = Session.getInstance(properties, new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(emailProperties.getUsername(), emailProperties.getPassword());
		}
	});

	try {
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(emailProperties.getUsername()));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

		message.setSubject(messages.getMessageBy("label.pathological.reports").concat(" - ").concat(messages.getMessageBy("label.recover.password")));
		message.setText(createBody(emailProperties.getApplicationCtxPath(), token));

		Transport.send(message);
	} catch (MessagingException mex) {
		mex.printStackTrace();
		throw new EmailException(messages.getMessageBy("message.email.exception"));
	}
}
 
Example 58
Project: MailCopier   File: MailCopier.java   Source Code and License 5 votes vote down vote up
public synchronized void receiveNext() throws MessagingException, IOException, Exception {
    if(messages.isEmpty()) {
        throw new RuntimeException("The Queue is empty.");
    }
    if(store == null || !store.isConnected()) {
        receiverConnect();
    }
    Message message = messages.peek();
    boolean haveAttach = receiveMultipartMessage(message, pManager.get_ReceiveFolder());
    messages.pop();
    messagesStr.pop();
    if(messages.isEmpty()) { // copy finalized
        set_mPointer(0);
        notifyReceiveCopyListeners();
        try {
            if(folder != null) {folder.close(true);}
        } catch(IllegalStateException | MessagingException ex) {
            pManager.writeLog(ex);
        } 
    } else {
        set_mPointer(mPointer + 1);
    }
    notifyMessagesListeners();
    if(!haveAttach) {
        throw new Exception("Message haven't attachment");
    }
}
 
Example 59
Project: Cognizant-Intelligent-Test-Scripter   File: Mailer.java   Source Code and License 5 votes vote down vote up
public static void send() {
    if (iCanSend()) {
        try {
            LOG.info("Sending Reports to Mail");
            sendMail();
        } catch (MessagingException | IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 60
Project: jaffa-framework   File: UserRequestMaintenanceTx.java   Source Code and License 5 votes vote down vote up
/** This method is invoked after the domain object has been created.*/
private void postCreate(UOW uow, UserRequestMaintenanceCreateInDto input, UserRequest domain, boolean fromPrevalidate)
throws FrameworkException, ApplicationExceptions {
    // .//GEN-END:_postCreate_1_be
    // Add custom code //GEN-FIRST:_postCreate_1
    EmailerBean email = new EmailerBean();
    UserRequest domainCreated = new UserRequest();
    Criteria criteria = new Criteria();
    criteria.setTable( UserRequestMeta.getName() );
    log.debug("This is the dto's final value" + input.getUrl());
    criteria.addCriteria(UserRequestMeta.USER_NAME, domain.getUserName());
    criteria.addCriteria(UserRequestMeta.FIRST_NAME , domain.getFirstName());
    criteria.addCriteria(UserRequestMeta.LAST_NAME , domain.getLastName());
    criteria.addCriteria(UserRequestMeta.CREATED_ON , domain.getCreatedOn());
    Iterator itr = uow.query(criteria).iterator();
    if (itr.hasNext())
        domainCreated = (UserRequest) itr.next();

    if (domainCreated != null) {
       try {
            String url = input.getUrl() + domainCreated.getRequestId();
            url = replaceAll(url , "Jaffa.User" , "Jaffa.Admin");
            String[] to = new String[] {"[email protected]"};
            email.sendMail(to, "request for user account" , url);

        } catch  (MessagingException e) {
            e.printStackTrace();
        }
    }

    input.setRequestId(domainCreated.getRequestId());

    // .//GEN-LAST:_postCreate_1
    // .//GEN-BEGIN:_postCreate_2_be
}