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:Sender.java

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

    // We need to pass info to the mail server as a Properties, since
    // JavaMail (wisely) allows room for LOTS of properties...
    Properties props = new Properties();

    // Your LAN must define the local SMTP server as "mailhost"
    // for this simple-minded version to be able to send mail...
    props.put("mail.smtp.host", "mailhost");

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

    try {//from   w ww.  j a  v a2 s .  c om
        // 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.
        mesg.setText(message_body);
        // XXX I18N: use setText(msgText.getText(), charset)

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

    } catch (MessagingException ex) {
        while ((ex = (MessagingException) ex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:domain.Employee.java

private String newPassword(String email) {

    if (email.equals("")) {
        throw new IllegalArgumentException("email must not be null");
    }//from   w w  w. j ava2  s  .c o m
    String pass = RandomStringUtils.randomAlphanumeric(8);
    //email the employee the password they can use to login

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String messagebody = String.format(
            "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n"
                    + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration",
            getName(), getEmail(), pass);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName()));
        msg.setSubject("Your account has been activated");
        msg.setText(messagebody);
        Transport.send(msg);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
    //hash the string and set the employee's password to the hashed one. USED SHA256
    System.out.println(pass);
    String hash = DigestUtils.sha256Hex(pass);
    return hash;
}

From source file:eu.scape_project.planning.application.Feedback.java

/**
 * Method responsible for sending feedback per mail.
 * /*from  ww  w  .  j  a  v  a 2 s .co m*/
 * @param userEmail
 *            email address of the user.
 * @param userComments
 *            comments from the user
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            the name of the application
 * @throws MailException
 *             if the feedback could not be sent
 */
public void sendFeedback(String userEmail, String userComments, String location, String applicationName)
        throws MailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        builder.append("Date: ").append(dateFormat.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Comments
        builder.append("Comments:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(userComments).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");
        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);

        log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback"));
    } catch (MessagingException e) {
        log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e);
        throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e);
    }
}

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

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

    outputFile.deleteOnExit();/* www .  ja v  a  2  s.c  om*/

    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.writeMessage(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:dk.netarkivet.common.utils.EMailUtils.java

/**
 * Send an email, possibly forgiving errors.
 *
 * @param to The recipient of the email. Separate multiple recipients with
 *           commas. Supports only adresses of the type 'john@doe.dk', not
 *           'John Doe <john@doe.dk>'
 * @param from The sender of the email.//  w  ww  .java 2 s.c  om
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @param forgive On true, will send the email even on invalid email
 *        addresses, if at least one recipient can be set, on false, will
 *        throw exceptions on any invalid email address.
 *
 *
 * @throws ArgumentNotValid If either parameter is null, if to, from or
 *                          subject is the empty string, or no recipient
 *                          can be set. If "forgive" is false, also on
 *                          any invalid to or from address.
 * @throws IOFailure If the message cannot be sent for some reason.
 */
public static void sendEmail(String to, String from, String subject, String body, boolean forgive) {
    ArgumentNotValid.checkNotNullOrEmpty(to, "String to");
    ArgumentNotValid.checkNotNullOrEmpty(from, "String from");
    ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject");
    ArgumentNotValid.checkNotNull(body, "String body");

    Properties props = new Properties();
    props.put(MAIL_FROM_PROPERTY_KEY, from);
    props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER));

    Session session = Session.getDefaultInstance(props);
    Message msg = new MimeMessage(session);

    // to might contain more than one e-mail address
    for (String toAddressS : to.split(",")) {
        try {
            InternetAddress toAddress = new InternetAddress(toAddressS.trim());
            msg.addRecipient(Message.RecipientType.TO, toAddress);
        } catch (AddressException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address",
                        e);
            }
        } catch (MessagingException e) {
            if (forgive) {
                log.warn("To address '" + toAddressS + "' could not be set in email", e);
            } else {
                throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e);
            }
        }
    }
    try {
        if (msg.getAllRecipients().length == 0) {
            throw new ArgumentNotValid("No valid recipients in '" + to + "'");
        }
    } catch (MessagingException e) {
        throw new ArgumentNotValid("Message invalid after setting" + " recipients", e);
    }

    try {
        InternetAddress fromAddress = null;
        fromAddress = new InternetAddress(from);
        msg.setFrom(fromAddress);
    } catch (AddressException e) {
        throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e);
    } catch (MessagingException e) {
        if (forgive) {
            log.warn("From address '" + from + "' could not be set in email", e);
        } else {
            throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e);
        }
    }

    try {
        msg.setSubject(subject);
        msg.setContent(body, MIMETYPE);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to
                + "'. Body:\n" + body, e);
    }
}

From source file:com.freemarker.mail.GMail.java

public boolean sendMailUsingJavaMailAPI(String to, String message1, HttpServletRequest req, String mid,
        String createdby, String pname, String mname) {
    String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateDataMapping(message1,
            getTemplateLocation(req), mid, createdby, pname, mname);
    String from = "analytixdstest@gmail.com";
    final String username = "analytixdstest@gmail.com";
    final String password = "analytix000";
    String host = "smtp.gmail.com";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from w w  w. j  av a 2s . co m*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setContent(FinalMessage, "text/html; charset=utf-8");
        message.saveChanges();
        message.setSubject("Analytix Test Mail");
        Transport.send(message);
        return true;
    } catch (MessagingException e) {
        return false;

    }
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

private void sendResponseMail(final Address sender, final String answer, final String subject)
        throws Exception {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("overseer@thenewoverseer.appspotmail.com", "Overseer"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sender.toString()));
    mimeMessage.setSubject("Re: " + subject);
    mimeMessage.setText(answer);/*from w w  w. j  av  a2 s.c o m*/
    Transport.send(mimeMessage);
}

From source file:Sender2.java

private void finish() {

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

    // create a message
    mesg = new MimeMessage(session);
}

From source file:com.rest.it.TestData.java

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    when(mailSender.createMimeMessage())
            .thenReturn(new MimeMessage(Session.getDefaultInstance(new Properties())));
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {//from  w  w  w . ja va  2 s  .co  m
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}