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:se.vgregion.mobile.services.SmtpErrorReportService.java

@Override
public void report(ErrorReport report) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    try {/*from  ww  w .jav  a 2  s  .c o m*/
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);

        String text = String.format(body, report.getPrinter().getName(), report.getDescription(),
                report.getReporter());
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("Failed sending error report via mail", e);
    }

}

From source file:com.email.SendEmailCalInvite.java

/**
 * Sends email based off of the section it comes from. This creates a
 * calendar invite object that is interactive by Outlook.
 *
 * @param eml EmailOutInviteModel// w  w w.j  a va 2  s.c  o m
 */
public static void sendCalendarInvite(EmailOutInvitesModel eml) {
    SystemEmailModel account = null;

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        //Get parts
        String FromAddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";"));
        String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";"));
        String emailSubject = "";
        BodyPart emailBody = body(eml);
        BodyPart inviteBody = null;

        if (eml.getHearingRoomAbv() == null) {
            emailSubject = eml.getEmailSubject() == null
                    ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody())
                    : eml.getEmailSubject();
            inviteBody = responseDueCalObject(eml, account);
        } else {
            emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject();
            inviteBody = inviteCalObject(eml, account, emailSubject);
        }

        //Set Email Parts
        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);
        Session session = Session.getInstance(properties, auth);
        MimeMessage smessage = new MimeMessage(session);
        Multipart multipart = new MimeMultipart("alternative");
        try {
            smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }
            for (String Cc : CCAddressess) {
                if (EmailValidator.getInstance().isValid(Cc)) {
                    smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc));
                }
            }
            smessage.setSubject(emailSubject);
            multipart.addBodyPart(emailBody);
            multipart.addBodyPart(inviteBody);
            smessage.setContent(multipart);
            if (Global.isOkToSendEmail()) {
                Transport.send(smessage);
            } else {
                Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject);
            }
            EmailOutInvites.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail.// w ww.  ja  v  a 2s  . co m
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

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

    Message 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());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;//ww  w .j a v  a 2s  . co  m
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

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

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;//  w  w w.  ja  va  2 s . c  o  m
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.spartasystems.holdmail.util.TestMailClient.java

public void sendEmail(String fromEmail, String toEmail, String subject, String textBody, String htmlBody) {
    try {//from   w w  w  .ja v  a2  s  . co m
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(subject);

        // Set the message
        createMultiMimePart(message, textBody, htmlBody);

        Transport.send(message);
    } catch (MessagingException e) {
        throw new HoldMailException("Failed to send email : " + e.getMessage(), e);
    }
}

From source file:com.mycompany.login.mb.EmailBean.java

public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("anderson.freitas@lifemed.com.br"));
    message.setRecipients(Message.RecipientType.TO, "anderson.freitas@lifemed.com.br");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitao foi aprovada: OS n" + this.os, "text/plain");

    Transport.send(message);/*from   w  w  w.  j a  va  2 s  .c o m*/

}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*from  ww w  . j  av a2 s . c  om*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();/*from www .  ja  va2  s.c o m*/
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}

From source file:com.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection.//  w  w w.  j  a v  a  2  s .c  om
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}