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:com.twinsoft.convertigo.engine.admin.services.projects.Deploy.java

@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
    if (!item.getName().endsWith(".car")) {
        ServiceUtils//from   w w  w.j  a v a 2s.  c om
                .addMessage(document, document.getDocumentElement(),
                        "The deployment of the project " + item.getName()
                                + " has failed. The archive file is not valid (.car required).",
                        "error", false);
    }

    super.doUpload(request, document, item);

    // Depending on client browsers, according to the documentation,
    // item.getName() can either return a full path file name, or
    // simply a file name.
    String projectArchive = item.getName();

    // Bugfix #1425
    int i = projectArchive.lastIndexOf('/');
    if (i == -1) {
        i = projectArchive.lastIndexOf('\\');
        if (i != -1) {
            projectArchive = projectArchive.substring(i + 1);
        }
    } else {
        projectArchive = projectArchive.substring(i + 1);
    }

    String projectName = projectArchive.substring(0, projectArchive.indexOf(".car"));

    Engine.theApp.databaseObjectsManager.deployProject(getRepository() + projectArchive, true, bAssembleXsl);

    if (Boolean.parseBoolean(
            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_NOTIFY_PROJECT_DEPLOYMENT))) {

        final String fUser = (String) request.getSession().getAttribute(SessionKey.ADMIN_USER.toString());
        final String fProjectName = projectName;

        new Thread(new Runnable() {
            public void run() {
                try {
                    Properties props = new Properties();

                    props.put("mail.smtp.host",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_HOST));
                    props.put("mail.smtp.socketFactory.port",
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_PORT));
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.put("mail.smtp.socketFactory.fallback", "false");

                    // Initializing
                    Session mailSession = Session.getInstance(props, new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(
                                    EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_SMTP_USER),
                                    EnginePropertiesManager
                                            .getProperty(PropertyName.NOTIFICATIONS_SMTP_PASSWORD));
                        }
                    });
                    MimeMessage message = new MimeMessage(mailSession);

                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                            EnginePropertiesManager.getProperty(PropertyName.NOTIFICATIONS_TARGET_EMAIL)));
                    message.setSubject("[trial] deployment of " + fProjectName + " by " + fUser);
                    message.setText(message.getSubject() + "\n" + "http://trial.convertigo.net/cems/projects/"
                            + fProjectName + "\n" + "https://trial.convertigo.net/cems/projects/"
                            + fProjectName);
                    Transport.send(message);
                } catch (MessagingException e1) {
                }
            }
        }).start();
    }

    String message = "The project '" + projectName + "' has been successfully deployed.";
    Engine.logAdmin.info(message);
    ServiceUtils.addMessage(document, document.getDocumentElement(), message, "message", false);
}

From source file:com.jvoid.customers.customer.service.CustomerMasterService.java

public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("test@example.com", "test123");
        }//from   w w  w  .  j a  v  a2 s  .  com
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("toaddress@example.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Reset Password");
        String content = "Your new password is " + password;
        message.setText(content);
        Transport.send(message);

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

From source file:com.mycompany.craftdemo.utility.java

public static void send(long phno, double price, double profit, String domain, String company) {
    HashMap<String, String> domainMap = new HashMap<>();
    domainMap.put("TMobile", "tmomail.net ");
    domainMap.put("ATT", "txt.att.net");
    domainMap.put("Sprint", "messaging.sprintpcs.com");
    domainMap.put("Verizon", "vtext.com");
    String to = phno + "@" + domainMap.get(domain); //change accordingly

    // Sender's email ID needs to be mentioned
    String from = "uni5prince@gmail.com"; //change accordingly
    final String username = "uni5prince"; //change accordingly
    final String password = "savageph8893"; //change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    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", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from   ww  w.  j  a  v a 2s . c  o  m
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Prices have gone up!!");

        // Now set the actual message
        message.setText("Hello Jane, Stock prices for " + company + " has reached to $" + price
                + " with profit of $" + profit);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

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

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;//  w w  w . ja  v  a 2  s .  co m
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:fr.aliacom.obm.common.calendar.MailSendTest.java

private EventMail newEventMail(List<Attendee> attendees, CalendarEncoding calendarEncoding)
        throws AddressException {
    return new EventMail(new InternetAddress("sender@test"), attendees, SUBJECT, BODY_TEXT, BODY_HTML, ICS,
            ICS_METHOD, calendarEncoding);
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content,
        List<MimeBodyPart> attachments) {
    MimeMessage mail = new MimeMessage(session);
    try {/* w ww  .  j a va 2 s .c o  m*/
        mail.setFrom(new InternetAddress(from));
        mail.setSubject(title);
        if (to != null) {
            mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }

        //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(content, "text/html;charset=utf-8");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        for (MimeBodyPart attachment : attachments) {
            multipart.addBodyPart(attachment);
        }

        mail.setContent(multipart);
        //         mail.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(mail);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from   www. ja v a 2  s .c o  m
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

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

From source file:de.elomagic.mag.AbstractTest.java

protected MimeMessage createMimeMessage(String filename) throws Exception {

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent("This is some text to be displayed inline", "text/plain");
    textPart.setDisposition(Part.INLINE);

    MimeBodyPart binaryPart = new MimeBodyPart();
    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    binaryPart.setContent(getOriginalMailAttachment(), "application/pdf");
    binaryPart.setDisposition(Part.ATTACHMENT);
    binaryPart.setFileName(filename);//from  w w w .ja  v a2  s  .com

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(textPart);
    mp.addBodyPart(binaryPart);

    MimeMessage message = new MimeMessage(greenMail.getImap().createSession());
    message.setRecipients(Message.RecipientType.TO,
            new InternetAddress[] { new InternetAddress("mailuser@localhost.com") });
    message.setSubject("Another test mail subject");
    message.setContent(mp);

    //
    return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup());
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

private InternetAddress emailAddress(Map.Entry<String, String> entry) {
    try {//from  w  w  w. j a  v a 2 s  .  c o m
        return StringUtils.isBlank(entry.getValue()) ? new InternetAddress(entry.getKey())
                : new InternetAddress(entry.getKey(), entry.getValue());
    } catch (Exception e) {
        throw new MailException(e,
                "Failed to send an email - unable to set a sender or recipient of '%s' <%s>: %s",
                entry.getKey(), entry.getValue(), e.getMessage());
    }
}

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();//from   w  w w  .j av a 2s  .co  m

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

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