Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

/**
 * Constructor that creates a new empty JavaMail {@link MimeMessage}
 */
public JavaMailGmailMessage() {
    this.source = new MimeMessage((Session) null);
}

From source file:SendMime.java

/** Do the work: send the mail to the SMTP server. */
public void doSend() throws IOException, MessagingException {

    // Create the Session object
    session = Session.getDefaultInstance(null, null);
    session.setDebug(true); // Verbose!

    try {//  www. j  a va  2  s  . co  m
        // create a message
        mesg = new MimeMessage(session);

        // From Address - this should come from a Properties...
        mesg.setFrom(new InternetAddress("nobody@host.domain"));

        // TO Address
        InternetAddress toAddress = new InternetAddress(message_recip);
        mesg.addRecipient(Message.RecipientType.TO, toAddress);

        // CC Address
        InternetAddress ccAddress = new InternetAddress(message_cc);
        mesg.addRecipient(Message.RecipientType.CC, ccAddress);

        // The Subject
        mesg.setSubject(message_subject);

        // Now the message body.
        Multipart mp = new MimeMultipart();

        BodyPart textPart = new MimeBodyPart();
        textPart.setText(message_body); // sets type to "text/plain"

        BodyPart pixPart = new MimeBodyPart();
        pixPart.setContent(html_data, "text/html");

        // Collect the Parts into the MultiPart
        mp.addBodyPart(textPart);
        mp.addBodyPart(pixPart);

        // Put the MultiPart into the Message
        mesg.setContent(mp);

        // Finally, send the message!
        Transport.send(mesg);

    } catch (MessagingException ex) {
        System.err.println(ex);
        ex.printStackTrace(System.err);
    }
}

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

private void sendEmail(User user, String email, Timestamp resetDate) throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    String resetCode = UserService.getResetCode(configuration.getSecret(), user.getNick(), email, resetDate);

    msg.addRecipient(RecipientType.TO, new InternetAddress(email));
    msg.setSubject("Your password @linux.org.ru");
    msg.setSentDate(new Date());
    msg.setText("?!\n\n"
            + "? ??  ?   ?? http://www.linux.org.ru/reset-password\n\n"
            + "  " + user.getNick() + ",  ?: " + resetCode + "\n\n"
            + "!");

    Transport.send(msg);//from  w  ww. j  a  v  a 2  s  .co m
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner/*from  w ww. j a  v a  2 s . co m*/
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:com.liferay.util.mail.MailEngine.java

public static void send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc, InternetAddress[] bcc,
        String subject, String body, boolean htmlFormat) throws MailEngineException {

    long start = System.currentTimeMillis();

    try {/*w ww . j  a v a2  s .  c  om*/
        Session session = getSession();

        Message msg = new MimeMessage(session);

        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, to);

        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, cc);
        }

        if (bcc != null) {
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        }

        msg.setSubject(subject);

        /*BodyPart bodyPart = new MimeBodyPart();
                
        if (htmlFormat) {
           bodyPart.setContent(body, "text/html");
        }
        else {
           bodyPart.setText(body);
        }
                
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);
                
        msg.setContent(multipart);*/

        if (htmlFormat) {
            msg.setContent(body, _TEXT_HTML);
        } else {
            msg.setContent(body, _TEXT_PLAIN);
        }

        _sendMessage(session, msg);
    } catch (SendFailedException sfe) {
        _log.error("From: " + from);
        _log.error("To: " + to);
        _log.error("Subject: " + subject);
        _log.error("Body: " + body);

        Logger.error(MailEngine.class, sfe.getMessage(), sfe);
    } catch (Exception e) {
        throw new MailEngineException(e);
    }

    long end = System.currentTimeMillis();

    _log.debug("Sending mail takes " + (end - start) + " seconds");
}

From source file:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java

/**
 * ??/*w w  w.j a v  a  2s  . c  om*/
 * @param originator 
 * @param recipients ?
 * @param subject ??
 * @return 
 * @throws EnterpriseException ?
 */
private Message createMessage(final InternetAddress originator,
        final Map<RecipientType, InternetAddress> recipients, final String subject) throws EnterpriseException {
    Validate.isTrue(recipients.size() > 0);
    try {
        final MimeMessage message = new MimeMessage(session);
        if (originator != null) {
            message.setFrom(originator);
        }
        for (final Entry<RecipientType, InternetAddress> recipient : recipients.entrySet()) {
            message.addRecipient(recipient.getKey(), recipient.getValue());
        }
        message.setSubject(subject, CHARSET);
        return message;
    } catch (final MessagingException e) {
        throw new EnterpriseException(e);
    }
}

From source file:cc.kune.core.server.mail.MailServiceDefault.java

@Override
public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body,
        final boolean isHtml, final String... tos) {
    if (smtpSkip) {
        return;/*from w w w  . ja  v a  2s  .c  om*/
    }

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);
    for (final String to : tos) {
        try {
            message.setFrom(new InternetAddress(from));
            // In case we should use utf8 also in address:
            // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // If additional header should be added
            // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
            final String formatedSubject = subject.getString();
            message.setSubject(formatedSubject, "utf-8");
            final String formatedBody = body.getString();
            if (isHtml) {
                // message.setContent(formatedBody, "text/html");
                message.setText(formatedBody, "UTF-8", "html");
            } else {
                message.setText(formatedBody, "UTF-8");
            }
            // Send message
            Transport.send(message);
        } catch (final AddressException e) {
        } catch (final MessagingException e) {
            final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s",
                    from, subject, to);
            log.error(error, e);
            // Better not to throw exceptions because users emails can be wrong...
            // throw new DefaultException(error, e);
        }
    }
}

From source file:de.hska.ld.core.service.impl.MailServiceImpl.java

@Override
public void sendMail(String fullName, String email, String templateFileName, Map<String, Object> model) {
    ;//ww  w . j  a  va2  s  . c o m
    if (Boolean.parseBoolean(env.getProperty("email.enabled"))) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
        model.put("dear", bundle.getString("email.dear"));
        model.put("fullName", fullName);
        model.put("greeting", bundle.getString("email.greeting"));

        String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                "templates/mail/" + templateFileName, "UTF-8", model);

        Properties properties = getMailProperties();

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MAIL_PROPERTIES.getProperty("email.username"),
                        MAIL_PROPERTIES.getProperty("email.password"));
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(MAIL_PROPERTIES.getProperty("email.from.system"));
            helper.setTo(email);
            helper.setSubject(model.containsKey("subject") ? (String) model.get("subject") : "");
            helper.setText(text, true);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {

    String passwordDesencriptada = Desencriptar(password2);

    try {/*from  w w w. j  av a2  s  .  c  o  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 ha recibido tu solicitud. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + passwordDesencriptada + "");

        // 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:eu.openanalytics.rsb.component.EmailDepositHandlerTestCase.java

@Test
public void handleJob() throws Exception {
    final MimeMessage mimeMessage = new MimeMessage((Session) null);
    final MimeMessageHelper mmh = new MimeMessageHelper(mimeMessage, true);
    mmh.setReplyTo("test@test.com");
    mmh.setText("test job");
    mmh.addAttachment("r-job-sample.zip", new ClassPathResource("data/r-job-sample.zip"),
            Constants.ZIP_CONTENT_TYPE);

    final DepositEmailConfiguration depositEmailConfiguration = mock(PersistedDepositEmailConfiguration.class);
    when(depositEmailConfiguration.getApplicationName()).thenReturn(TEST_APPLICATION_NAME);
    final Message<MimeMessage> message = MessageBuilder.withPayload(mimeMessage)
            .setHeader(EmailDepositHandler.EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration).build();

    emailDepositHandler.handleJob(message);

    final ArgumentCaptor<MultiFilesJob> jobCaptor = ArgumentCaptor.forClass(MultiFilesJob.class);
    verify(messageDispatcher).dispatch(jobCaptor.capture());

    final MultiFilesJob job = jobCaptor.getValue();
    assertThat(job.getApplicationName(), is(TEST_APPLICATION_NAME));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_SUBJECT_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_ADDRESSEE_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_TO_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_REPLY_CC_META_NAME), is(true));
    assertThat(job.getMeta().containsKey(EmailDepositHandler.EMAIL_BODY_META_NAME), is(true));
    assertThat(job.getSource(), is(Source.EMAIL));
    job.destroy();/*from  w  w  w  . j av  a  2s.  c o m*/
}