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:io.stallion.utils.GeneralUtils.java

public static boolean isValidEmailAddress(String email) {
    boolean result = true;
    try {//  w  ww .  java 2 s. co m
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
    } catch (AddressException ex) {
        result = false;
    }
    return result;
}

From source file:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {// w w w  . ja va2s.c  o m
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }/*from  ww w . j a v  a  2s  .  c  o  m*/
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}

From source file:de.tu_dortmund.ub.api.paaa.model.Patron.java

public void setEmail(String email) {

    try {//from   w  ww  .j  av a  2 s  . c  o m

        this.email = new InternetAddress(email);

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

From source file:it.infn.ct.security.actions.PassRecovery.java

private void sendMail(String code) throws MailException {
    javax.mail.Session session = null;//from w w  w.ja  va  2s. com
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        String title = user.getTitle() == null ? "" : user.getTitle();

        mailMsg.setFrom(new InternetAddress(mailFrom));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(user.getPreferredMail(),
                title + user.getGivenname() + " " + user.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname());
        mailBody = mailBody.replaceAll("_CODE_", code);

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateCardDetailsMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com", "Card Details Updated",
            "card_details_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Card Details Updated", message.getSubject());
    Assert.assertEquals(_CARD_DETAILS_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

private Address[] getAddressesFromString(final String str) throws AddressException {
    final List<Address> retval = new ArrayList<Address>();

    final String[] parts = str.split("[;, ]");
    for (String part : parts)
        if (part.length() > 0)
            retval.add(new InternetAddress(part));
    return retval.toArray(new Address[0]);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();//from ww  w . j  a v a2s .com

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:com.bia.monitor.service.EmailService.java

/**
 * bcc -- incase you need to be copied on emails
 *
 * @return//from  ww w.j  av a 2  s  .  co  m
 * @throws AddressException
 */
private InternetAddress[] getBCC() throws AddressException {
    if (bcc != null) {
        return bcc;
    }
    bcc = new InternetAddress[2];
    bcc[0] = new InternetAddress("mdshannan@gmail.com");
    bcc[1] = new InternetAddress("atefahmed@gmail.com");
    return bcc;
}