Example usage for javax.mail.internet MimeMessage setText

List of usage examples for javax.mail.internet MimeMessage setText

Introduction

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

Prototype

@Override
public void setText(String text) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

Usage

From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *///from  w  w  w. j  av a 2s.  c o  m
public boolean send() {

    try {
        // 2005-11-27 RSC always requires authentication.
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", host.getAddress());
        /*
         * 2005-11-27 RSC
         * Since webmail.us is starting to make other ports available
         * as Comcast blocks port 25.
         */
        props.put("mail.smtp.port", host.getPort());

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

        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:com.fsrin.menumine.common.message.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *//*from   w  w w  .  j  av  a2  s . c  o  m*/
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:mx.uatx.tesis.managebeans.IndexMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {/*from   www  .  j  av a2 s  . co  m*/
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Sends an email to the user asking they follow a link to validate their email address
 * @param id DB key to be embedded in response link
 * @param email Address target//from  w  w w. j  av a  2 s . com
 */
private void sendVerificationEmail(String id, String email, ServletRequest req) {
    m_logger.debug("sending mail");
    String from = "admin@" + m_serverName;
    Properties props = new Properties();
    props.put("mail.smpt.host", m_serverName);
    props.put("mail.from", from);
    Session session = Session.getInstance(props, null);
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, email);
        msg.setSubject("Verify your PaperMiner email address");
        msg.setSentDate(new Date());
        // FIXME: the verify address needs to be more robust
        msg.setText("Dear " + email.substring(0, email.indexOf("@")) + ",\n\n"
                + "PaperMiner has sent you this message to validate that the email address which you "
                + "supplied is able to receive notifications from our server.\n"
                + "To complete the verification process, please click the link below.\n\n" + "http://"
                + m_serverName + ":8080/PaperMiner/pm/vfy?id=" + id + "\n\n"
                + "If you are unable to click the link above, verification can be completed by copying "
                + "and pasting it into the address bar of your web browser.\n\n" + "Your email address is "
                + email + ". Use this to log in when returning to the PaperMiner site.\n"
                + "You can update your email address, or change your TROVE API key at any time through the "
                + "\"Manage Your Details\" option of the User menu, but an email change will require re-validation.\n\n"
                + "Paper Miner Administrator");
        Transport.send(msg);
        m_logger.info("Verifcation mail sent to " + email);
    } catch (MessagingException ex) {
        m_logger.error("Email verification to " + email + " failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e109");
    }
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessUnauthorizedEmailSimpleText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.FALSE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);//from ww w .java2  s  . c o m
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));
    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(0, event.getMessages().size());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailSimpleText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);

    MessageListener mockListener2 = mock(MessageListener.class);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);/*from   w w w.j  a  v  a 2s  .  co m*/
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Simple text Email test", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(0, message.getAttachmentsSize());
    assertEquals(0, message.getAttachments().size());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/plain; charset=" + System.getProperty("file.encoding"), message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:org.jumpmind.metl.core.runtime.flow.FlowRuntime.java

protected void sendNotifications(Notification.EventType eventType) {
    if (notifications != null && notifications.size() > 0) {
        Transport transport = null;// w  w  w  .  j a  v a2s  . c  o m
        Date date = new Date();
        flowParameters.put("_date", DateFormatUtils.format(date, DATE_FORMAT));
        flowParameters.put("_time", DateFormatUtils.format(date, TIME_FORMAT));

        try {
            for (Notification notification : notifications) {
                if (notification.getEventType().equals(eventType.toString())) {
                    log.info("Sending notification '" + notification.getName() + "' of level '"
                            + notification.getLevel() + "' and type '" + notification.getNotifyType() + "'");
                    transport = mailSession.getTransport();
                    MimeMessage message = new MimeMessage(mailSession.getSession());
                    message.setSentDate(new Date());
                    message.setRecipients(RecipientType.BCC, notification.getRecipients());
                    message.setSubject(
                            FormatUtils.replaceTokens(notification.getSubject(), flowParameters, true));
                    message.setText(FormatUtils.replaceTokens(notification.getMessage(), flowParameters, true));
                    try {
                        transport.sendMessage(message, message.getAllRecipients());
                    } catch (MessagingException e) {
                        log.error("Failure while sending notification", e);
                    }
                }
            }
        } catch (MessagingException e) {
            log.error("Failure while preparing notification", e);
        } finally {
            mailSession.closeTransport(transport);
        }
    }
}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail inkl. Transfercodierung.
 * @param email//from www  .  ja  v  a  2s  .c  o  m
 * @throws MessagingException
 * @throws IOException
 */
public String createMail3(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    byte[] outputBytes;

    // Transfercodierung anwenden
    if (config.getTranscodeDescription().equals(Config.BASE64)) {
        outputBytes = encodeBase64(mailAsBytes);
    } else if (config.getTranscodeDescription().equals(Config.QP)) {
        outputBytes = encodeQuotedPrintable(mailAsBytes);
    } else {
        outputBytes = mailAsBytes;
    }
    email.setText(outputBytes);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    MimeMessage msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(outputBytes));
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 3");
        throw e;
    }

    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT,
            "Content-Transfer-Encoding: " + config.getTranscodeDescription()));
}

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

public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm,
        HttpServletRequest request) {//from  w ww  .ja v  a  2s  .  c o m

    //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.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override//from  ww  w. j  av a  2s . c  o  m
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}