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:com.waveerp.sendMail.java

public void sendMsgSSL(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.socketFactory.port", strPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/* w  ww .  ja va 2s  .  com*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    //log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass );

}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

public void setFrom(String from) throws EmailMessageException {
    if (from == null) {
        from = "DO_NOT_REPLY";
    }/*w  ww  . jav  a2s  .c o  m*/
    try {
        InternetAddress[] addresses = InternetAddress.parse(from);
        if (addresses.length != 1) {
            throw new EmailMessageException("One and only one \"from\" address may be specified, "
                    + addresses.length + " were found: " + from);
        }
        fromAddress = addresses[0];

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception parsing the email addresses");
    }
}

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

/**
 * Builds the InternetAddress for the sender (from) 
 * /*w  ww  .  ja  va2s  .c  o  m*/
 * Step 1: use PROP_ORIGINATOR
 * 
 * Last Step : Use the default address.
 * 
 * Content Author name if provided. If name not specified, it takes Content Creator name. 
 * If content creator does not exists, the default from address will be returned.
 * 
 * @return Generated InternetAddress[] array.
 * @throws AddressException
 */
private InternetAddress[] buildSenderFromAddress() throws AddressException {
    // Generate FROM address (Content author)
    InternetAddress[] result = null;
    Map<QName, Serializable> properties = messageFileInfo.getProperties();
    String defaultFromAddress = imapService.getDefaultFromAddress();

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

    /**
     * Go for the author property
     */
    if (properties.containsKey(ContentModel.PROP_AUTHOR)) {
        String author = (String) properties.get(ContentModel.PROP_AUTHOR);
        try {

            if (!(author == null || author.isEmpty())) {
                StringBuilder contentAuthor = new StringBuilder();
                contentAuthor.append("\"").append(author).append("\" <").append(defaultFromAddress).append(">");
                result = InternetAddress.parse(contentAuthor.toString());
                return result;
            }

        } catch (AddressException e) {
            // try next step
        }
    }

    if (properties.containsKey(ContentModel.PROP_CREATOR)) {
        String author = (String) properties.get(ContentModel.PROP_CREATOR);
        try {

            StringBuilder contentAuthor = new StringBuilder();
            contentAuthor.append("\"").append(author).append("\" <").append(defaultFromAddress).append(">");
            result = InternetAddress.parse(contentAuthor.toString());
            return result;

        } catch (AddressException e) {
            // try next step
        }
    }

    /**
     * Last Step : Get the Default address
     */
    try {
        result = InternetAddress.parse(defaultFromAddress);
        return result;
    } catch (AddressException e) {
        logger.warn(String.format("Wrong email address '%s'.", defaultFromAddress), e);
    }
    result = InternetAddress.parse(DEFAULT_EMAIL_FROM);
    return result;

}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public void sendEmail(String to, String subject, String body) {
    final String fromUser = fromMail;
    final String passUser = password;
    Properties props = new Properties();
    props.put("mail.smtp.host", smtp);
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.auth", mailAuth);
    props.put("mail.smtp.port", port);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromUser, passUser);
        }/*  w w w  . j a  v  a2 s .  c om*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromUser));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.surfnet.coin.teams.control.AddMemberController.java

/**
 * Called after submitting the add members form
 *
 * @param form     {@link nl.surfnet.coin.teams.domain.InvitationForm} from the session
 * @param result   {@link org.springframework.validation.BindingResult}
 * @param request  {@link javax.servlet.http.HttpServletRequest}
 * @param modelMap {@link org.springframework.ui.ModelMap}
 * @return the name of the form if something is wrong
 *         before handling the invitation,
 *         otherwise a redirect to the detailteam url
 * @throws IOException if something goes wrong handling the invitation
 *//*from  w  ww  .  j ava  2 s  .  c o m*/
@RequestMapping(value = "/doaddmember.shtml", method = RequestMethod.POST)
public String addMembersToTeam(@ModelAttribute(TokenUtil.TOKENCHECK) String sessionToken,
        @ModelAttribute("invitationForm") InvitationForm form, BindingResult result, HttpServletRequest request,
        @RequestParam() String token, SessionStatus status, ModelMap modelMap) throws IOException {
    TokenUtil.checkTokens(sessionToken, token, status);
    Person person = (Person) request.getSession().getAttribute(LoginInterceptor.PERSON_SESSION_KEY);
    addNewMemberRolesToModelMap(person, form.getTeamId(), modelMap);

    final boolean isAdminOrManager = controllerUtil.hasUserAdministrativePrivileges(person,
            request.getParameter(TEAM_PARAM));
    if (!isAdminOrManager) {
        status.setComplete();
        throw new RuntimeException("Requester (" + person.getId()
                + ") is not member or does not have the correct " + "privileges to add (a) member(s)");
    }
    final boolean isAdmin = controllerUtil.hasUserAdminPrivileges(person, request.getParameter(TEAM_PARAM));
    // if a non admin tries to add a role admin or manager -> make invitation for member
    if (!(isAdmin || Role.Member.equals(form.getIntendedRole()))) {
        form.setIntendedRole(Role.Member);
    }
    Validator validator = new InvitationFormValidator();
    validator.validate(form, result);

    if (result.hasErrors()) {
        modelMap.addAttribute(TEAM_PARAM, controllerUtil.getTeamById(form.getTeamId()));
        return "addmember";
    }

    // Parse the email addresses to see whether they are valid
    InternetAddress[] emails;
    try {
        emails = InternetAddress.parse(getAllEmailAddresses(form));
    } catch (AddressException e) {
        result.addError(new FieldError("invitationForm", "emails", "error.wrongFormattedEmailList"));
        return "addmember";
    }

    Locale locale = localeResolver.resolveLocale(request);
    doInviteMembers(emails, form, locale);
    AuditLog.log("User {} sent invitations for team {}, with role {} to addresses: {}", person.getId(),
            form.getTeamId(), form.getIntendedRole(), emails);

    status.setComplete();
    modelMap.clear();
    return "redirect:detailteam.shtml?team=" + URLEncoder.encode(form.getTeamId(), UTF_8) + "&view="
            + ViewUtil.getView(request);
}

From source file:esg.node.components.notification.ESGNotifier.java

private boolean sendNotification(String userid, String userAddress, String messageText) {
    Message msg = null;/* ww  w . j  av  a2  s . c  o  m*/
    boolean success = false;
    String myAddress = null;

    try {
        msg = new MimeMessage(session);
        msg.setHeader("X-Mailer", "ESG DataNode IshMailer");
        msg.setSentDate(new Date());
        myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov");
        msg.setFrom(new InternetAddress(myAddress));
        msg.setSubject(subject + "ESG File Update Notification");

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress));
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress));

        msg.setText(messageText);

        Transport.send(msg);
        success = true;
    } catch (MessagingException ex) {
        log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject
                + ")\n" + messageText + "\n", ex);
    }

    msg = null; //gc niceness

    return success;
}

From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java

private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray)
        throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients",
            FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);

    final Sender sender = Bennu.getInstance().getSystemSender();

    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualizao");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    Multipart multipart = new MimeMultipart();

    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);//from w  ww .  ja v a 2 s. co m

    Transport.send(message);
}

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

@Async
public void download(String type, String version, String token, String subject, String fromUser,
        String fromName, final String toUser, final String toName, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}",
                    new Object[] { type, version, token }).getMessage());
    model.put("name", toName);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8",
            model);//from  w  w  w.jav a  2s .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);
    }
}

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

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error/*from   www . jav a2  s.c om*/
 */
private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter = null;

    try {
        messageFormatter = TransportUtils.getMessageFormatter(msgContext);
    } catch (AxisFault axisFault) {
        throw new BaseTransportException("Unable to get the message formatter to use");
    }

    WSMimeMessage message = new WSMimeMessage(session);
    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
        message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
    } else {
        if (smtpFromAddress != null) {
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        message.setRecipients(Message.RecipientType.CC,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    InternetAddress[] trpBccArr = null;
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
    }

    InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0)
            + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)];
    if (trpBccArr != null) {
        System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length);
    }
    if (smtpBccAddresses != null) {
        System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length);
    }
    if (mergedBcc != null) {
        message.setRecipients(Message.RecipientType.BCC, mergedBcc);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        message.setSubject(outInfo.getSubject());
    } else {
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    // if a custom message id is set, use it
    if (msgContext.getMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    ByteArrayOutputStream baos = null;
    String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());
    DataHandler dataHandler = null;
    MimeMultipart mimeMultiPart = null;

    OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement();
    if (firstChild != null) {

        if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) {
            baos = new ByteArrayOutputStream();
            OMNode omNode = firstChild.getFirstOMChild();

            if (omNode != null && omNode instanceof OMText) {
                Object dh = ((OMText) omNode).getDataHandler();
                if (dh != null && dh instanceof DataHandler) {
                    dataHandler = (DataHandler) dh;
                }
            }
        } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) {
            if (firstChild instanceof OMSourcedElementImpl) {
                baos = new ByteArrayOutputStream();
                try {
                    firstChild.serializeAndConsume(baos);
                } catch (XMLStreamException e) {
                    handleException("Error serializing 'text' payload from OMSourcedElement", e);
                }
                dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                        MailConstants.TEXT_PLAIN);
            } else {
                dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN);
            }
        } else {

            baos = new ByteArrayOutputStream();
            messageFormatter.writeTo(msgContext, format, baos, true);

            // create the data handler
            dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                    contentType);

            String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
            if (mFormat == null) {
                mFormat = defaultMailFormat;
            }

            if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
                mimeMultiPart = new MimeMultipart();
                MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
                mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
                MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
                mimeBodyPart2.setDataHandler(dataHandler);
                mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
                mimeMultiPart.addBodyPart(mimeBodyPart1);
                mimeMultiPart.addBodyPart(mimeBodyPart2);

            } else {
                message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
            }
        }
    }

    try {
        if (mimeMultiPart == null) {
            message.setDataHandler(dataHandler);
        } else {
            message.setContent(mimeMultiPart);
        }
        Transport.send(message);

    } catch (MessagingException e) {
        handleException("Error creating mail message or sending it to the configured server", e);

    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

public void addReplyTo(List<String> replyAddress) throws EmailMessageException {
    for (String address : replyAddress) {
        try {//from   w  w  w .  j  a va 2  s.co  m
            InternetAddress[] list = InternetAddress.parse(address);
            replyToAddress.addAll(Arrays.asList(list));
        } catch (Exception ex) {
            throw new EmailMessageException("Exception parsing the email address: " + address);
        }
    }
}