Example usage for javax.mail.internet InternetAddress InternetAddress

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

Introduction

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

Prototype

public InternetAddress(String address) throws AddressException 

Source Link

Document

Constructor.

Usage

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//from w w  w  . j  a v  a 2s .c om
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//  w  ww.  j a va 2 s  .c  om
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:com.redhat.rhn.common.messaging.SmtpMail.java

/** {@inheritDoc} */
public void setFrom(String from) {
    try {//from  w w w. jav  a  2 s  . c o  m
        message.setFrom(new InternetAddress(from));
    } catch (AddressException me) {
        String msg = "Malformed address in traceback configuration: " + from;
        log.warn(msg);
        throw new JavaMailException(msg, me);
    } catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " + me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}

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

@Override
public void checkDependencies() throws Exception {
    emailTos = Config.requireList(EMAIL_TO);
    emailHost = Config.requireString(EMAIL_HOST);
    emailPort = Config.requireString(EMAIL_PORT);
    emailSmtpAuth = Config.requireString(EMAIL_SMTP_AUTH);
    emailTls = Config.requireString(EMAIL_START_TLS_ENABLE);
    emailFrom = Config.requireString(EMAIL_FROM);
    emailEncryptedPassword = Config.requireString(EMAIL_ENCRYPTED_PASSWORD);
    emailMaxAttachmentMB = Config.requirePositiveInteger(EMAIL_ATTACHMENT_MAX_MB);
    emailIncludeQsub = Config.getBoolean(EMAIL_SEND_QSUB);
    clusterHost = Config.getString(CLUSTER_HOST);

    new InternetAddress(emailFrom).validate();
    for (final String email : emailTos) {
        new InternetAddress(email).validate();
    }//from   w  ww  . j a va  2 s.c  om
}

From source file:com.mnt.base.mail.MailHelper.java

public static void sendMail(String mailType, String mailTos, Map<String, Object> infoMap) {

    String[] mailtemplate = loadMailTemplate(mailType);

    if (mailtemplate != null && mailtemplate.length == 2) {
        String from = BaseConfiguration.getProperty("mail_server_email");
        String subject = buildMailContent(mailtemplate[0], infoMap, false);
        String mailContent = buildMailContent(mailtemplate[1], infoMap, true);

        Message msg = new MimeMessage(smtpSession);
        try {/*from  w  ww.  j  a  v  a2  s .c o  m*/
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTos, false));
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            msg.setContent(mailContent, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());

            Transport.send(msg);
        } catch (Exception e) {
            log.error("fail to send the mail: " + msg, e);
        }
    }
}

From source file:org.beanfuse.notification.mail.AbstractMailNotifier.java

private void addRecipient(MimeMessage message, RecipientType recipientType, String[] recipients)
        throws AddressException, MessagingException {
    if (null != recipients) {
        for (int i = 0; i < recipients.length; i++) {
            InternetAddress to = new InternetAddress(recipients[i].trim());
            message.addRecipient(recipientType, to);
        }//from   ww w.  j a  v  a 2 s .c  o m
    }
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

private void setEmailRecipients(MimeMessage msg, List<String> addresses, RecipientType type)
        throws EmailException {
    InternetAddress[] inetAddr = new InternetAddress[addresses.size()];
    try {/*from  w w  w  . j a v a 2 s.  c  om*/
        for (int i = 0; i < addresses.size(); ++i) {
            String addr = addresses.get(i);
            if (MiscUtils.isEmpty(addr))
                throw new IllegalArgumentException("model.get" + type + " has empty address at index:" + i);
            addr = addr.trim();
            doValidateEmailAddress(addr);
            inetAddr[i] = new InternetAddress(addr);
        }

        msg.setRecipients(type, inetAddr);
    } catch (MessagingException e) {
        throw new EmailAddressException(e);
    }

}

From source file:gt.dakaik.common.Common.java

public static MimeMessage createEmail(String to, String subject, String bodyText) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(sendMailFrom));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);/*  www  . j  a v  a2s.c  om*/
    email.setText(bodyText);
    return email;
}

From source file:com.fsrin.menumine.common.message.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *///  w  w w .  j  a  v  a2  s.  c om
public boolean send() {

    try {

        Properties props = new Properties();

        props.put("mail.smtp.host", host.getAddress());

        if (host.useAuthentication()) {

            props.put("mail.smtp.auth", "true");
        }

        Session s = Session.getInstance(props, null);

        s.setDebug(true);

        //            PasswordAuthentication pa = new PasswordAuthentication(host
        //                    .getUsername(), host.getPassword());
        //
        //            URLName url = new URLName(host.getAddress());
        //
        //            s.setPasswordAuthentication(url, pa);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());

        e.printStackTrace();
        throw new RuntimeException(e);

    }

    return true;
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from ww  w  .ja va2  s. co m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}