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.gitlab.anlar.lunatic.server.ServerTest.java

private Message createBaseMessage(String from, String to, String subject, Session session)
        throws MessagingException {
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(to) });
    msg.setSentDate(new Date());
    msg.setSubject(subject);/* ww w. j a  va2s  .  com*/

    return msg;
}

From source file:org.cgiar.dapa.ccafs.tpe.service.impl.TPEMailService.java

@Override
public void notifyUser(final String userEmail, final Map<String, Object> templateVariables) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setTo(userEmail);/*from www  .j  a v a2  s. com*/
            message.setFrom(new InternetAddress(adminEmail));
            message.setSubject(SUBJECT_USER);
            String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "templates/notify-user.vm", "UTF-8", templateVariables);
            log.info(body);
            message.setText(body, true);
        }
    };
    this.mailSender.send(preparator);

}

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

private void assertTextCalendarContentTransferEncodingIsCorrect(CalendarEncoding encoding) throws Exception {
    String icsContent = IOUtils.toString(getClass().getResourceAsStream("meetingWithOneAttendee.ics"));
    EventMail eventMail = new EventMail(new InternetAddress("sender@test"),
            ImmutableList.of(newAttendee("attendee1")), SUBJECT, BODY_TEXT, BODY_HTML, icsContent, ICS_METHOD,
            encoding);//from w w w. j a  v a2 s  .  c o  m
    String content = writeEventMail(eventMail);
    LineIterator lineIterator = new LineIterator(new StringReader(content));
    boolean textCalendarFound = false;

    while (lineIterator.hasNext()) {
        if (lineIterator.next().contains("Content-Type: text/calendar")) {
            textCalendarFound = true;
            break;
        }
    }

    assertThat(textCalendarFound).isTrue();
    assertThat(lineIterator.next()).contains("Content-Transfer-Encoding: " + encoding.getValue());
}

From source file:ru.org.linux.user.RegisterRequestValidator.java

@Override
public void validate(Object o, Errors errors) {
    RegisterRequest form = (RegisterRequest) o;

    /*//w w  w. j a va 2s.  c  o  m
    Nick validate
     */

    String nick = form.getNick();

    if (Strings.isNullOrEmpty(nick)) {
        errors.rejectValue("nick", null, "  nick");
    }

    if (nick != null && !StringUtil.checkLoginName(nick)) {
        errors.rejectValue("nick", null, " ? ?");
    }

    if (nick != null && nick.length() > User.MAX_NICK_LENGTH) {
        errors.rejectValue("nick", null, "?  ? ?");
    }

    /*
    Password validate
     */

    String password = Strings.emptyToNull(form.getPassword());
    String password2 = Strings.emptyToNull(form.getPassword2());

    if (Strings.isNullOrEmpty(password)) {
        errors.reject("password", null, "    ?");
    }
    if (Strings.isNullOrEmpty(password2)) {
        errors.reject("password2", null, "    ?");
    }

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(password, null, "   ? ? ");
    }

    if (form.getPassword2() != null && form.getPassword() != null
            && !form.getPassword().equals(form.getPassword2())) {
        errors.reject(null, "   ?");
    }

    if (!Strings.isNullOrEmpty(form.getPassword()) && form.getPassword().length() < MIN_PASSWORD_LEN) {
        errors.reject("password", null,
                "?  , ? : "
                        + MIN_PASSWORD_LEN);
    }

    /*
    Email validate
     */

    if (Strings.isNullOrEmpty(form.getEmail())) {
        errors.rejectValue("email", null, "?  e-mail");
    } else {
        try {
            InternetAddress mail = new InternetAddress(form.getEmail());
            checkEmail(mail, errors);
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    /*
    Rules validate
     */

    if (Strings.isNullOrEmpty(form.getRules()) || !"okay".equals(form.getRules())) {
        errors.reject("rules", null, "  ??? ? ");
    }
}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*from  w w w  .  j a v  a 2 s  .  c  o m*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

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

protected void assignRecipient(SendingMessage sendingMessage, MimeMessage message) throws MessagingException {
    InternetAddress internetAddress = new InternetAddress(sendingMessage.getAddress().trim());
    message.setRecipient(Message.RecipientType.TO, internetAddress);
}

From source file:com.ayu.filter.RegularService.java

@Async
public void sendSSLMail(String text, String toMail) {

    final String username = "clouddefenceids";
    final String password = "";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
        message.setSubject("Forgot Password");
        message.setText(text);

        Transport.send(message);

        System.out.println("Done");

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

From source file:mitm.application.djigzo.james.mailets.MailAddressHandlerTest.java

@Test
public void mailAddressHandlerRetrySuccess() throws Exception {
    final int retries = 4;

    final MutableInt count = new MutableInt();

    final MutableBoolean action = new MutableBoolean(false);

    MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
        @Override//from  ww w . jav  a 2 s .  c om
        public void handleUser(User user) throws MessagingException {
            count.increment();

            if (count.intValue() <= retries) {
                throw new ConstraintViolationException("Dummy ConstraintViolationException", null, "");
            }

            action.setValue(true);
        }
    };

    MailAddressHandler handler = new MailAddressHandler(sessionManager, userWorkflow, actionExecutor,
            eventHandler, retries);

    Collection<MailAddress> recipients = MailAddressUtils
            .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com"));

    handler.handleMailAddresses(recipients);

    assertTrue(action.booleanValue());
    assertEquals(retries + 1, count.intValue());
}

From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java

/**
 * Creates empty mail./* w  w w. jav  a 2 s . com*/
 *
 * @param build build.
 * @param listener listener.
 * @return empty mail.
 * @throws MessagingException exception if any.
 */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }/*from  ww  w. java2 s  .  c o  m*/

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}