Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * //from  w  ww  .  j  a  v  a 2 s  .c  om
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 *
 * @param addressTo//from w w  w .  j  a v a 2  s . co  m
 * @param subject
 * @param message
 *
 */
private void send(InternetAddress[] addressTo, String subject, String message) {
    try {
        MimeMessage msg = new MimeMessage(createSession());
        msg.setFrom(new InternetAddress(USERNAME));
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
    } catch (Exception ex) {
        //logger.warn(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);// w w  w  .j  ava 2 s.c om
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:com.thinkbiganalytics.metadata.sla.SlaEmailService.java

/**
 * Send an email/*from  ww w  . j a va 2s.c  o m*/
 *
 * @param to      the user(s) to send the email to
 * @param subject the subject of the email
 * @param body    the email body
 */
public void sendMail(String to, String subject, String body) {

    try {
        if (testConnection()) {
            MimeMessage message = mailSender.createMimeMessage();
            String fromAddress = StringUtils.defaultIfBlank(emailConfiguration.getFrom(),
                    emailConfiguration.getUsername());
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
            log.debug("Email send to {}", to);
        }
    } catch (MessagingException ex) {
        log.error("Exception while sending mail : {}", ex.getMessage());
        Throwables.propagate(ex);

    }
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*  w w  w.j  av a2 s  .c  o m*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 * ? E-mail ?./*from  ww  w. jav  a 2 s  .c  o m*/
 *
 * @param request    ?  web-
 * @param exception ?
 * @return , ? ??? ? ?
 */
private String sendEmailToAdmin(HttpServletRequest request, Exception exception) {
    InternetAddress mail;
    String adminEmailAddress = configuration.getAdminEmailAddress();

    try {
        mail = new InternetAddress(adminEmailAddress, true);
    } catch (AddressException e) {
        return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress;
    }
    StringBuilder text = new StringBuilder();

    if (exception.getMessage() == null) {
        text.append(exception.getClass().getName());
    } else {
        text.append(exception.getMessage());
    }
    text.append("\n\n");

    Template tmpl = Template.getTemplate(request);
    //    text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri"));
    String mainUrl = "<unknown>";

    mainUrl = configuration.getMainUrl();

    text.append("Main URL: ").append(mainUrl).append(request.getServletPath());

    if (request.getQueryString() != null) {
        text.append('?').append(request.getQueryString()).append('\n');
    }
    text.append('\n');

    text.append("IP: " + request.getRemoteAddr() + '\n');

    text.append(" Headers: ");
    Enumeration enu = request.getHeaderNames();
    while (enu.hasMoreElements()) {
        String paramName = (String) enu.nextElement();
        text.append("\n         ").append(paramName).append(": ").append(request.getHeader(paramName));
    }
    text.append("\n\n");

    StringWriter exceptionStackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(exceptionStackTrace));
    text.append(exceptionStackTrace.toString());

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    try {
        emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));
        emailMessage.addRecipient(Message.RecipientType.TO, mail);
        emailMessage.setSubject("Linux.org.ru: " + exception.getClass());
        emailMessage.setSentDate(new Date());
        emailMessage.setText(text.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("An error occured while creating e-mail!", e);
        return EMAIL_NOT_SENT;
    }
    try {
        Transport.send(emailMessage);
        return EMAIL_SENT;
    } catch (Exception e) {
        return EMAIL_NOT_SENT;
    }
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to/*from w  w w. ja  va2  s  .c o  m*/
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from  w w w.j a v a 2s  . c o  m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:org.apache.james.protocols.smtp.netty.NettyStartTlsSMTPServerTest.java

@Test
public void startTlsShouldWorkWhenUsingJavamail() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    server = createServer(createProtocol(Optional.<ProtocolHandler>of(hook)),
            Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
    server.bind();/*from w w  w.j  a  v a  2s .co m*/
    SMTPTransport transport = null;

    try {
        InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", bindedAddress.getHostName());
        mailProps.put("mail.smtp.port", bindedAddress.getPort());
        mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName());
        mailProps.put("mail.smtp.socketFactory.fallback", "false");
        mailProps.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(mailProps);

        InternetAddress[] rcpts = new InternetAddress[] { new InternetAddress("valid@localhost") };
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

        transport = (SMTPTransport) mailSession.getTransport("smtps");

        transport.connect(new Socket(bindedAddress.getHostName(), bindedAddress.getPort()));
        transport.sendMessage(message, rcpts);

        assertThat(hook.getQueued()).hasSize(1);
    } finally {
        if (transport != null) {
            transport.close();
        }
    }
}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }//from w  w w .j  a v a2  s  .c  o m

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}