Example usage for javax.mail.internet InternetAddress parse

List of usage examples for javax.mail.internet InternetAddress parse

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress parse.

Prototype

public static InternetAddress[] parse(String addresslist) throws AddressException 

Source Link

Document

Parse the given comma separated sequence of addresses into InternetAddress objects.

Usage

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /*from  w w w. ja  v  a  2s . c  o  m*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:org.alfresco.repo.imap.ContentModelMessage.java

/**
 * Generate the "to" address.//from ww w  . j ava2s  .c om
 * 
 * Step 1: Use PROP_ADDRESSEE
 * 
 * Last Step: Use the default address
 * 
 * @return Generated TO address {@code <user>@<current.domain>}
 * @throws AddressException
 */
private InternetAddress[] buildRecipientToAddress() throws AddressException {
    InternetAddress[] result = null;

    Map<QName, Serializable> properties = messageFileInfo.getProperties();

    /**
     * Step 1 : Get the ADDRESSEE if it exists
     */
    if (properties.containsKey(ContentModel.PROP_ADDRESSEE)) {
        String addressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
        try {
            result = InternetAddress.parse(addressee);
            return result;
        } catch (AddressException e) {
            // try next step
        }
    }

    //      final String escapedUserName = AuthenticationUtil.getFullyAuthenticatedUser().replaceAll("[/,\\,@]", ".");
    //      final String userDomain = DEFAULT_EMAIL_TO.split("@")[1];
    //      String userName = escapedUserName + "@" + userDomain;
    //      try
    //      {
    //          result = InternetAddress.parse(userName);
    //          return result;        
    //      }
    //      catch (AddressException e)
    //      {
    //      }

    /**
     * Last Step : Get the Default address
     */
    String defaultToAddress = imapService.getDefaultToAddress();

    try {
        result = InternetAddress.parse(defaultToAddress);
        return result;
    } catch (AddressException e) {
        logger.warn(String.format("Wrong email address '%s'.", defaultToAddress), e);
    }
    result = InternetAddress.parse(DEFAULT_EMAIL_TO);
    return result;

}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void passwd(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}",
                    new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model);

    try {/*www . j av  a  2  s.c o m*/
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Sends a mail message. The content must be provided as MimeBodyPart objects.
 *
 * @param from      Sender's email address.
 * @param to        Recipient's email address.
 * @param cc        Email address for CC.
 * @param bcc       Email address for BCC.
 * @param subject   Subject text for the email.
 * @param bodyParts The body parts to insert into the message.
 * @throws SystemException        if an unexpected error occurs.
 * @throws ConfigurationException if a configuration error occurs.
 *//*ww w  . ja  v  a  2  s .co  m*/
public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts)
        throws ConfigurationException, SystemException {

    initEventLog();

    try {
        Properties props = new Properties();

        Configuration config = Aksess.getConfiguration();
        String host = config.getString("mail.host");
        if (host == null) {
            throw new ConfigurationException("mail.host");
        }

        // I noen tilfeller nsker vi at all epost skal g til en testadresse
        String catchAllTo = config.getString("mail.catchall.to");
        boolean catchallExists = catchAllTo != null && catchAllTo.contains("@");
        if (catchallExists) {
            StringBuilder prefix = new StringBuilder(" (original recipient: " + to);
            if (cc != null) {
                prefix.append(", cc: ").append(cc);
            }
            if (bcc != null) {
                prefix.append(", bcc: ").append(bcc);
            }
            prefix.append(") ");
            subject = prefix + subject;
            to = catchAllTo;
            cc = null;
            bcc = null;
        }

        props.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(props);

        boolean debug = config.getBoolean("mail.debug", false);
        if (debug) {
            session.setDebug(true);
        }

        // Opprett message, sett attributter
        MimeMessage message = new MimeMessage(session);
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress[] = InternetAddress.parse(to);

        message.setFrom(fromAddress);

        if (toAddress.length > 1) {
            message.setRecipients(Message.RecipientType.BCC, toAddress);
        } else {
            message.setRecipients(Message.RecipientType.TO, toAddress);
        }
        if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }

        message.setSubject(subject, "ISO-8859-1");
        message.setSentDate(new Date());

        Multipart mp = new MimeMultipart();
        for (MimeBodyPart bodyPart : bodyParts) {
            mp.addBodyPart(bodyPart);
        }
        message.setContent(mp);

        // Send meldingen
        Transport.send(message);

        eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null);

        // Logg sending
        log.info("Sending email to " + to + " with subject " + subject);
    } catch (MessagingException e) {
        String errormessage = "Subject: " + subject + " | Error: " + e.getMessage();
        eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null);
        log.error("Error sending mail", e);
        throw new SystemException("Error sending email to : " + to + " with subject " + subject, e);
    }
}

From source file:Implement.DAO.CommonDAOImpl.java

@Override
public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from  w ww  . j  ava 2  s .  co m
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(messageContent, "text/html; charset=utf-8");
    Transport.send(message);
    return true;

}

From source file:org.apache.synapse.transport.mail.MailTransportSender.java

/**
 * Send the given message over the Mail transport
 *
 * @param msgCtx the axis2 message context
 * @throws AxisFault on error/*ww  w.ja va 2 s.  c o  m*/
 */
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    MailOutTransportInfo mailOutInfo = null;

    if (targetAddress != null) {
        if (targetAddress.startsWith(MailConstants.TRANSPORT_NAME)) {
            targetAddress = targetAddress.substring(MailConstants.TRANSPORT_NAME.length() + 1);
        }

        if (msgCtx.getReplyTo() != null
                && !AddressingConstants.Final.WSA_NONE_URI.equals(msgCtx.getReplyTo().getAddress())
                && !AddressingConstants.Final.WSA_ANONYMOUS_URL.equals(msgCtx.getReplyTo().getAddress())) {

            String replyTo = msgCtx.getReplyTo().getAddress();
            if (replyTo.startsWith(MailConstants.TRANSPORT_NAME)) {
                replyTo = replyTo.substring(MailConstants.TRANSPORT_NAME.length() + 1);
            }
            try {
                mailOutInfo = new MailOutTransportInfo(new InternetAddress(replyTo));
            } catch (AddressException e) {
                handleException("Invalid reply address/es : " + replyTo, e);
            }
        } else {
            mailOutInfo = new MailOutTransportInfo(smtpFromAddress);
        }

        try {
            mailOutInfo.setTargetAddresses(InternetAddress.parse(targetAddress));
        } catch (AddressException e) {
            handleException("Invalid target address/es : " + targetAddress, e);
        }
    } else if (outTransportInfo != null && outTransportInfo instanceof MailOutTransportInfo) {
        mailOutInfo = (MailOutTransportInfo) outTransportInfo;
    }

    if (mailOutInfo != null) {
        try {
            sendMail(mailOutInfo, msgCtx);
        } catch (MessagingException e) {
            handleException("Error generating mail message", e);
        } catch (IOException e) {
            handleException("Error generating mail message", e);
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:com.netspective.commons.message.SendMail.java

protected Address[] getAddresses(Value value) throws AddressException, MessagingException {
    if (value.isListValue()) {
        String[] addressTexts = value.getTextValues();
        Address[] result = new Address[addressTexts.length];
        for (int i = 0; i < addressTexts.length; i++)
            result[i] = new InternetAddress(addressTexts[i]);
        return result;
    } else/*from   w  w  w.j av  a  2 s  .  c o  m*/
        return InternetAddress.parse(value.getTextValue());
}

From source file:bioLockJ.module.agent.MailAgent.java

private Message getMimeMessage() throws Exception {
    final Message message = new MimeMessage(getSession());
    message.setFrom(new InternetAddress(emailFrom));
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getRecipients()));
    message.setSubject("BioLockJ " + Config.requireString(Config.PROJECT_NAME) + " " + status);
    message.setContent(getContent());/* w  w w  .  j a  v  a  2 s .  c o  m*/
    return message;
}

From source file:org.apache.lens.server.query.QueryEndNotifier.java

/** Send mail.
 *
 * @param host                      the host
 * @param port                      the port
 * @param email                     the email
 * @param mailSmtpTimeout           the mail smtp timeout
 * @param mailSmtpConnectionTimeout the mail smtp connection timeout */
public static void sendMail(String host, String port, Email email, int mailSmtpTimeout,
        int mailSmtpConnectionTimeout) throws Exception {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.timeout", mailSmtpTimeout);
    props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email.getFrom()));
    for (String recipient : email.getTo().trim().split("\\s*,\\s*")) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
    }/* ww w  .  ja  v  a  2s.com*/
    if (email.getCc() != null && email.getCc().length() > 0) {
        for (String recipient : email.getCc().trim().split("\\s*,\\s*")) {
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient));
        }
    }
    message.setSubject(email.getSubject());
    message.setSentDate(new Date());

    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setText(email.getMessage());
    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messagePart);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void registe(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/registe/confirm?userid={}&token={}",
            new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/registe.vm", "UTF-8",
            model);//from w ww  .j av  a2s .  c o  m

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}