Example usage for javax.mail.internet InternetAddress setPersonal

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

Introduction

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

Prototype

public void setPersonal(String name, String charset) throws UnsupportedEncodingException 

Source Link

Document

Set the personal name.

Usage

From source file:com.flexive.shared.FxMailUtils.java

private static InternetAddress[] encodePersonal(InternetAddress[] addresses)
        throws UnsupportedEncodingException {
    if (addresses == null) {
        return null;
    }//from w  w  w. j a v  a 2 s .c o  m
    for (InternetAddress address : addresses) {
        if (address.getPersonal() != null) {
            address.setPersonal(address.getPersonal(), "UTF-8");
        }
    }
    return addresses;
}

From source file:com.flexive.shared.FxMailUtils.java

private static InternetAddress createAddress(String from)
        throws AddressException, UnsupportedEncodingException {
    final InternetAddress address = new InternetAddress(from);
    if (address.getPersonal() != null) {
        // encode name which is more likely to use non-ASCII characters
        address.setPersonal(address.getPersonal(), "UTF-8");
    }//from w  w  w .ja  v a2 s.  c  o  m
    return address;
}

From source file:com.silverpeas.util.MailUtil.java

public static synchronized InternetAddress getAuthorizedEmailAddress(String pFrom, String personalName)
        throws AddressException, UnsupportedEncodingException {
    String senderAddress = getAuthorizedEmail(pFrom);
    InternetAddress address = new InternetAddress(senderAddress, true);
    // - If email is authorized (senderAddress.equals(pFrom)), use it as it (personalName)
    // - If email is not authorized (!senderAddress.equals(pFrom)), use default one and default
    //   personal name too (notificationPersonalName)
    String personal = senderAddress.equals(pFrom) ? personalName : notificationPersonalName;
    if (StringUtil.isDefined(personal)) {
        address.setPersonal(personal, CharEncoding.UTF_8);
    }/*from   ww  w .  ja v a 2s.c  o  m*/
    return address;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Parses the adresslist./*from  www. j  a va  2  s. co m*/
 * 
 * @param addresslist
 * @param charset
 * @return
 */
public static InternetAddress[] parseInternetAddress(String addresslist, String charset)
        throws MessagingException {

    if (addresslist != null) {
        addresslist = addresslist.replace(';', ',');
        InternetAddress[] addressArray = InternetAddress.parse(addresslist);

        if (addressArray != null) {
            for (InternetAddress address : addressArray) {
                String personal = address.getPersonal();
                if (personal != null) {
                    try {
                        address.setPersonal(personal, charset);
                    } catch (UnsupportedEncodingException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }

        return addressArray;
    }

    return null;
}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }//from   ww  w  . j a  va2 s.c o  m

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

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

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void assignFromAddress(SendingMessage sendingMessage, MimeMessage msg) throws MessagingException {
    InternetAddress[] internetAddresses = InternetAddress.parse(sendingMessage.getFrom());
    for (InternetAddress internetAddress : internetAddresses) {
        if (StringUtils.isNotEmpty(internetAddress.getPersonal())) {
            try {
                internetAddress.setPersonal(internetAddress.getPersonal(), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                throw new MessagingException("Unsupported encoding type", e);
            }/*from   w w  w .  j a  v  a 2  s . c  o  m*/
        }
    }

    if (internetAddresses.length == 1) {
        msg.setFrom(internetAddresses[0]);
    } else {
        msg.addFrom(internetAddresses);
    }
}

From source file:com.enonic.esl.net.Mail.java

/**
 * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is
 * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance.
 * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p>
 *///from  w ww. ja  va 2s  .  c  om
public void send() throws ESLException {
    // smtp server
    Properties smtpProperties = new Properties();
    if (smtpHost != null) {
        smtpProperties.put("mail.smtp.host", smtpHost);
        System.setProperty("mail.smtp.host", smtpHost);
    } else {
        smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST);
        System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST);
    }
    Session session = Session.getDefaultInstance(smtpProperties, null);

    try {
        // create message
        Message msg = new MimeMessage(session);
        // set from address
        InternetAddress addressFrom = new InternetAddress();
        if (from_email != null) {
            addressFrom.setAddress(from_email);
        }
        if (from_name != null) {
            addressFrom.setPersonal(from_name, ENCODING);
        }
        ((MimeMessage) msg).setFrom(addressFrom);

        if ((to.size() == 0 && bcc.size() == 0) || subject == null
                || (message == null && htmlMessage == null)) {
            LOG.error("Missing data. Unable to send mail.");
            throw new ESLException("Missing data. Unable to send mail.");
        }

        // set to:
        for (int i = 0; i < to.size(); ++i) {
            String[] recipient = to.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo);
        }

        // set bcc:
        for (int i = 0; i < bcc.size(); ++i) {
            String[] recipient = bcc.get(i);
            InternetAddress addressTo = null;
            try {
                addressTo = new InternetAddress(recipient[1]);
            } catch (Exception e) {
                System.err.println("exception on address: " + recipient[1]);
                continue;
            }
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo);
        }

        // set cc:
        for (int i = 0; i < cc.size(); ++i) {
            String[] recipient = cc.get(i);
            InternetAddress addressTo = new InternetAddress(recipient[1]);
            if (recipient[0] != null) {
                addressTo.setPersonal(recipient[0], ENCODING);
            }
            ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo);
        }

        // Setting subject and content type
        ((MimeMessage) msg).setSubject(subject, ENCODING);

        if (message != null) {
            message = RegexpUtil.substituteAll("\\\\n", "\n", message);
        }

        // if there are any attachments, treat this as a multipart message.
        if (attachments.size() > 0) {
            BodyPart messageBodyPart = new MimeBodyPart();
            if (message != null) {
                ((MimeBodyPart) messageBodyPart).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler);
            }
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // add all attachments
            for (int i = 0; i < attachments.size(); ++i) {
                Object obj = attachments.get(i);
                if (obj instanceof String) {
                    System.err.println("attachment is String");
                    messageBodyPart = new MimeBodyPart();
                    ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING);
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof File) {
                    messageBodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource((File) obj);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else if (obj instanceof FileItem) {
                    FileItem fileItem = (FileItem) obj;
                    messageBodyPart = new MimeBodyPart();
                    FileItemDataSource fds = new FileItemDataSource(fileItem);
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setFileName(fds.getName());
                    multipart.addBodyPart(messageBodyPart);
                } else {
                    // byte array
                    messageBodyPart = new MimeBodyPart();
                    ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING);
                    messageBodyPart.setDataHandler(new DataHandler(bads));
                    messageBodyPart.setFileName(bads.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            msg.setContent(multipart);
        } else {
            if (message != null) {
                ((MimeMessage) msg).setText(message, ENCODING);
            } else {
                DataHandler dataHandler = new DataHandler(
                        new ByteArrayDataSource(htmlMessage, "text/html", ENCODING));
                ((MimeMessage) msg).setDataHandler(dataHandler);
            }
        }

        // send message
        Transport.send(msg);
    } catch (AddressException e) {
        String MESSAGE_30 = "Error in email address: " + e.getMessage();
        LOG.warn(MESSAGE_30);
        throw new ESLException(MESSAGE_30, e);
    } catch (UnsupportedEncodingException e) {
        String MESSAGE_40 = "Unsupported encoding: " + e.getMessage();
        LOG.error(MESSAGE_40, e);
        throw new ESLException(MESSAGE_40, e);
    } catch (SendFailedException sfe) {
        Throwable t = null;
        Exception e = sfe.getNextException();
        while (e != null) {
            t = e;
            if (t instanceof SendFailedException) {
                e = ((SendFailedException) e).getNextException();
            } else {
                e = null;
            }
        }
        if (t != null) {
            String MESSAGE_50 = "Error sending mail: " + t.getMessage();
            throw new ESLException(MESSAGE_50, t);
        } else {
            String MESSAGE_50 = "Error sending mail: " + sfe.getMessage();
            throw new ESLException(MESSAGE_50, sfe);
        }
    } catch (MessagingException e) {
        String MESSAGE_50 = "Error sending mail: " + e.getMessage();
        LOG.error(MESSAGE_50, e);
        throw new ESLException(MESSAGE_50, e);
    }
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format).// www  . ja va  2s  . co m
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:org.grouter.common.mail.MailHandler.java

/**
 * @param mimeMessage// ww  w . j a v  a 2s  .  c  o m
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
private void createHeader(MimeMessage mimeMessage, MailDto mailDto)
        throws UnsupportedEncodingException, MessagingException {

    //from
    InternetAddress fromAddress = new InternetAddress(mailDto.getFrom());
    fromAddress.setPersonal(mailDto.getSenderNote(), ENCODING);
    mimeMessage.setSender(fromAddress);

    //to

    List<String> senders = mailDto.getTo();
    InternetAddress[] toAddress = getRecipients(senders);

    List<String> sendersCc = mailDto.getCc();
    InternetAddress[] toAddressCc = getRecipients(sendersCc);

    List<String> sendersBcc = mailDto.getBcc();
    InternetAddress[] toAddressBcc = getRecipients(sendersBcc);

    mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
    mimeMessage.setRecipients(Message.RecipientType.CC, toAddressCc);
    mimeMessage.setRecipients(Message.RecipientType.BCC, toAddressBcc);

    //subject
    mimeMessage.setSubject(mailDto.getSubject(), ENCODING);

    //sent date
    mimeMessage.setSentDate(new Date());
}

From source file:org.itracker.model.User.java

public InternetAddress getEmailAddress() {

    if (null == getEmail() || getEmail().trim().length() == 0) {
        log.warn("getEmailAddress: failed to get eMail for user " + getLogin() + " (" + getId() + ")");
        return null;
    }/*  www  . j  ava  2 s.c  o m*/
    final InternetAddress adr;
    try {
        adr = new InternetAddress(getEmail());
        try {
            adr.setPersonal(getFullName(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.warn("getEmailAddress: unsupported encoding for setting personal: utf-8", e);
        }
        return adr;
    } catch (AddressException e1) {
        log.error("getEmailAddress: failed to parse email '" + getEmail() + "' for user " + getLogin() + " ("
                + getId() + "), returning null", e1);
        return null;
    }

}