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() 

Source Link

Document

Default constructor.

Usage

From source file:cl.preguntame.controller.PlataformaController.java

@ResponseBody
@RequestMapping(value = "/email", method = RequestMethod.POST)
public String correo(HttpServletRequest req) {

    try {/*from   w w w  .jav  a2 s. c  om*/
        String host = "smtp.gmail.com";

        Properties prop = System.getProperties();

        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", "hector.riquelme1169@gmail.com");
        prop.put("mail.smtp.password", "rriiqquueellmmee");
        prop.put("mail.smtp.port", 587);
        prop.put("mail.smtp.auth", "true");

        Session sesion = Session.getDefaultInstance(prop, null);
        MimeMessage mensaje = new MimeMessage(sesion);

        mensaje.setFrom(new InternetAddress());
        mensaje.setRecipient(Message.RecipientType.TO, new InternetAddress("hector.riquelme1169@gmail.com"));
        mensaje.setSubject("CONTACTO MIS CONCEPTOS");
        mensaje.setText(req.getParameter("mensaje_contacto"));

        Transport transport = sesion.getTransport("smtp");
        transport.connect(host, "hector.riquelme1169@gmail.com", "rriiqquueellmmee");
        transport.sendMessage(mensaje, mensaje.getAllRecipients());

        transport.close();

    } catch (Exception e) {

    }

    return req.getParameter("mensaje_contacto") + "  -  " + req.getParameter("email_contacto");
}

From source file:org.tsm.concharto.lab.LabJavaMail.java

private void sendConfirmationEmail(User user) {
    //mailSender.setHost("skipper");
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getEmail());/*from w w w. j a  v a 2  s .c o  m*/
    String messageText = StringUtils.replace(WELCOME_MESSAGE, PARAM_NAME, user.getUsername());
    message.setText(messageText);
    message.setSubject(WELCOME_SUBJECT);
    message.setFrom("<Concharto Notifications> notify@concharto.com");

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    InternetAddress from = new InternetAddress();
    from.setAddress("notify@concharto.com");
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal("Concharto Notifications");
        mimeMessage.addRecipient(Message.RecipientType.TO, to);
        mimeMessage.setSubject(WELCOME_SUBJECT);
        mimeMessage.setText(messageText);
        mimeMessage.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mailSender.setHost("localhost");
    mailSender.send(mimeMessage);

    /*
    Confirm your registration with Concharto
            
    Hello sanmi,
            
    Welcome to the Concharto community!
            
    Please click on this link to confirm your registration: http://www.concharto.com/member/confirm.htm?id=:confirmation 
            
    You can find out more about us at http://wiki.concharto.com/wiki/About.
            
    If you were not expecting this email, just ignore it, no further action is required to terminate the request.
     */
}

From source file:org.tsm.concharto.web.feedback.FeedbackController.java

public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm,
        HttpServletRequest request) {/*from ww w  .j a v a  2  s.  com*/

    //prepare the user info
    String requestInfo = getBrowserInfo(request);

    StringBuffer messageText = new StringBuffer(feedbackForm.getBody())
            .append("\n\n=============================================================\n").append(requestInfo);

    InternetAddress from = new InternetAddress();
    from.setAddress(feedbackForm.getEmail());
    InternetAddress to = new InternetAddress();
    to.setAddress(sendFeedbackToAddress);
    try {
        from.setPersonal(feedbackForm.getName());
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(FEEDBACK_SUBJECT + feedbackForm.getSubject());
        message.setText(messageText.toString());
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

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 w  w .  j a va 2 s  .  co m
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:org.jasig.schedassist.impl.reminder.DefaultReminderServiceImplTest.java

/**
 * SA-21 verify service continues to process reminders after failed email.
 * /*ww  w.  j a  v  a  2  s.  co m*/
 * @throws InputFormatException 
 * 
 */
@Test
public void testPersistedReminderWithInvalidEmailAddress() throws InputFormatException {
    java.util.Date now = new java.util.Date();
    java.util.Date later = DateUtils.addHours(now, 1);
    DefaultEventUtilsImpl eventUtils = new DefaultEventUtilsImpl(new NullAffiliationSourceImpl());
    AvailableBlock targetBlock = AvailableBlockBuilder.createBlock(now, later);

    PersistedReminderImpl persisted = new PersistedReminderImpl();
    persisted.setOwnerId(1L);
    persisted.setReminderId(1L);
    persisted.setRecipientId("recipientid");
    persisted.setSendTime(now);
    persisted.setBlockStartTime(now);
    persisted.setBlockEndTime(later);

    MockCalendarAccount recipient = new MockCalendarAccount();
    recipient.setDisplayName("Some Visitor");
    recipient.setEmailAddress("bogus@nowhere.com");

    MockCalendarAccount account = new MockCalendarAccount();
    account.setDisplayName("Some Person");
    account.setEmailAddress("somebodyelse@nowhere.com");
    MockScheduleOwner owner = new MockScheduleOwner(account, 1L);
    AvailableBlock block = AvailableBlockBuilder.createBlock(new Date(), DateUtils.addMinutes(new Date(), 30));
    VEvent event = eventUtils.constructAvailableAppointment(block, owner, new MockScheduleVisitor(recipient),
            "test event");

    ReminderDao reminderDao = mock(ReminderDao.class);
    OwnerDao ownerDao = mock(OwnerDao.class);
    ICalendarAccountDao calendarAccountDao = mock(ICalendarAccountDao.class);
    SchedulingAssistantService schedAssistService = mock(SchedulingAssistantService.class);
    MailSender mailSender = mock(MailSender.class);

    List<PersistedReminderImpl> pending = new ArrayList<PersistedReminderImpl>();
    pending.add(persisted);

    when(reminderDao.getPendingReminders()).thenReturn(pending);
    when(ownerDao.locateOwnerByAvailableId(1L)).thenReturn(owner);
    when(calendarAccountDao.getCalendarAccount("recipientid")).thenReturn(recipient);

    when(schedAssistService.getExistingAppointment(targetBlock, owner)).thenReturn(event);
    SMTPAddressFailedException smtpFailure = new SMTPAddressFailedException(new InternetAddress(), "DATA", 550,
            "illegal alias");

    MailSendException exception = new MailSendException("failed", smtpFailure);

    doThrow(exception).when(mailSender).send(isA(SimpleMailMessage.class));

    DefaultReminderServiceImpl reminderService = new DefaultReminderServiceImpl();
    reminderService.setCalendarAccountDao(calendarAccountDao);
    reminderService.setMailSender(mailSender);
    reminderService.setMessageSource(messageSource);
    reminderService.setOwnerDao(ownerDao);
    reminderService.setReminderDao(reminderDao);
    reminderService.setSchedulingAssistantService(schedAssistService);

    reminderService.setEventUtils(eventUtils);
    List<IReminder> pendingCheck = reminderService.getPendingReminders();
    Assert.assertEquals(1, pendingCheck.size());
    Assert.assertTrue(reminderService.shouldSend(pendingCheck.get(0)));
    reminderService.processPendingReminders();

    verify(reminderDao, times(1)).deleteEventReminder(isA(ReminderImpl.class));
}