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:edu.washington.iam.tools.IamMailSender.java

private MimeMessage genMimeMessage(IamMailMessage msg) {
    MimeMessage mime = mailSender.createMimeMessage();
    try {//from w  w  w  .j  av  a2s.c  om
        mime.setRecipients(RecipientType.TO, InternetAddress.parse(msg.getTo()));
        mime.setSubject(msg.makeSubstitutions(msg.getSubject()));
        mime.setReplyTo(InternetAddress.parse(replyTo));
        mime.setFrom(new InternetAddress(msg.getFrom()));
        mime.addHeader("X-Auto-Response-Suppress", "NDR, OOF, AutoReply");
        mime.addHeader("Precedence", "Special-Delivery, never-bounce");
        mime.setText(msg.makeSubstitutions(msg.getText()));
    } catch (MessagingException e) {
        log.error("iam mail build fails: " + e);
    }
    return mime;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/* w ww. j  av a 2 s . c  o m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * @param message/*w  w  w  .  j av a  2  s  . c  o m*/
 *            Email message being built.
 * @param emailFromString
 *            Email Address of person sending the email.
 * @throws MessagingException
 *             Thrown if there are problems creating the message.
 */
public void setFrom(final MimeMessage message, final String emailFromString) throws MessagingException {
    InternetAddress fromAddress = new InternetAddress(emailFromString);
    message.setFrom(fromAddress);
}

From source file:org.libreplan.importers.notifications.ComposeMessage.java

public boolean composeMessageForUser(EmailNotification notification) {
    // Gather data about EmailTemplate needs to be used
    Resource resource = notification.getResource();
    EmailTemplateEnum type = notification.getType();
    Locale locale;//from   w w w . j a  v a 2 s  . c  om
    Worker currentWorker = getCurrentWorker(resource.getId());

    UserRole currentUserRole = getCurrentUserRole(notification.getType());

    if (currentWorker != null && currentWorker.getUser().isInRole(currentUserRole)) {
        if (currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE)) {
            locale = new Locale(System.getProperty("user.language"));
        } else {
            locale = new Locale(currentWorker.getUser().getApplicationLanguage().getLocale().getLanguage());
        }

        EmailTemplate currentEmailTemplate = findCurrentEmailTemplate(type, locale);

        if (currentEmailTemplate == null) {
            LOG.error("Email template is null");
            return false;
        }

        // Modify text that will be composed
        String text = currentEmailTemplate.getContent();
        text = replaceKeywords(text, currentWorker, notification);

        String receiver = currentWorker.getUser().getEmail();

        setupConnectionProperties();

        final String username = usrnme;
        final String password = psswrd;

        // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
        Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Send message
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

            String subject = currentEmailTemplate.getSubject();
            message.setSubject(subject);

            message.setText(text);

            Transport.send(message);

            return true;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            if (receiver == null) {
                Messagebox.show(
                        _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
                        _("Error"), Messagebox.OK, Messagebox.ERROR);
            }
        }
    }
    return false;
}

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

/**
 * Method responsible for sending a bug report per mail.
 * /*from   www.  j  av a 2s  .  c om*/
 * @param userEmail
 *            email address of the user.
 * @param errorDescription
 *            error description given by the user.
 * @param exception
 *            the exception causing the bug/error.
 * @param requestUri
 *            request URI where the error occurred
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            application name
 * @param plan
 *            the plan where the exception occurred
 * @throws MailException
 *             if the bug report could not be sent
 */
public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri,
        String location, String applicationName, Plan plan) 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();
        // Date
        builder.append("Date: ").append(DATE_FORMAT.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");

        // Plan
        if (plan == null) {
            builder.append("No plan available.").append("\n\n");
        } else {
            builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n");
            builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n");
        }

        // Description
        builder.append("Description:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(errorDescription).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");

        // Request URI
        builder.append("Request URI: ").append(requestUri).append("\n\n");

        // Exception
        if (exception == null) {
            builder.append("No exception available.").append("\n");
        } else {
            builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n");
            builder.append("Exception message: ").append(exception.getMessage()).append("\n");

            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            builder.append("Stacktrace:\n");
            builder.append(SEPARATOR_LINE);
            builder.append(writer.toString());
            builder.append(SEPARATOR_LINE);
        }

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(),
                config.getString("mail.feedback"));

        String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.";
        Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO",
                userMessage, user);
        try {
            utx.begin();
            em.persist(notification);
            utx.commit();
        } catch (Exception e) {
            log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e);
        }

    } catch (MessagingException e) {
        throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to "
                + config.getString("mail.feedback"), e);
    }
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {//w w w .j a  v a2s  .  c o  m
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:org.fireflow.service.email.send.MailSenderImpl.java

/**
 * TODO ?//from   w ww  .  j  av  a2s . co  m
 * @param mailSession
 * @param mailMessage
 * @return
 * @throws MessagingException 
 * @throws AddressException 
 * @throws ServiceInvocationException
 */
private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage)
        throws AddressException, MessagingException {
    MimeMessage mimeMsg = new MimeMessage(mailSession);

    //1?set from
    //Assert.notNull(mailMessage.getFrom(),"From address must not be null");
    mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom()));

    //2?set mailto
    List<String> mailToList = mailMessage.getMailToList();
    InternetAddress[] addressList = new InternetAddress[mailToList.size()];
    for (int i = 0; i < mailToList.size(); i++) {
        String mailTo = mailToList.get(i);
        addressList[i] = new InternetAddress(mailTo);
    }
    mimeMsg.setRecipients(Message.RecipientType.TO, addressList);

    //3?set cc
    List<String> ccList = mailMessage.getCarbonCopyList();
    if (ccList != null && ccList.size() > 0) {
        addressList = new InternetAddress[ccList.size()];
        for (int i = 0; i < ccList.size(); i++) {
            String mailTo = ccList.get(i);
            addressList[i] = new InternetAddress(mailTo);
        }
        mimeMsg.setRecipients(Message.RecipientType.CC, addressList);
    }

    //4?set subject
    mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset());

    //5?set sentDate
    if (this.sentDate != null) {
        mimeMsg.setSentDate(sentDate);
    }

    //6?set email body
    Multipart multiPart = new MimeMultipart();
    MimeBodyPart bp = new MimeBodyPart();
    if (mailMessage.getBodyIsHtml())
        bp.setContent(mailMessage.getBody(),
                CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset());
    else
        bp.setText(mailMessage.getBody(), mailServiceDef.getCharset());

    multiPart.addBodyPart(bp);
    mimeMsg.setContent(multiPart);

    //7?set attachment
    //TODO ?

    return mimeMsg;
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java

public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException,
        SendFailedException, MessagingException, IOException {
    String fromAddress = email.getHeader(Message.Field.FROM);
    if (fromAddress == null) {
        throw new MessagingException("Unable to send without a 'from' address.");
    }// w  w  w.ja va  2s. co m

    // transform to a MimeMessage
    ArrayList<String> invalids = new ArrayList<String>();

    // convert and validate the 'from' address
    InternetAddress from = new InternetAddress(fromAddress, true);

    // convert and validate reply to addresses
    String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO);
    InternetAddress[] replyTo = emails2Internets(replyTos, invalids);

    // convert and validate the 'to' addresses
    String tos = email.getHeader(Message.Field.TO);
    InternetAddress[] to = emails2Internets(tos, invalids);

    // convert and validate 'cc' addresses
    String ccs = email.getHeader(EmailMessage.Field.CC);
    InternetAddress[] cc = emails2Internets(ccs, invalids);

    // convert and validate 'bcc' addresses
    String bccs = email.getHeader(EmailMessage.Field.BCC);
    InternetAddress[] bcc = emails2Internets(bccs, invalids);

    int totalRcpts = to.length + cc.length + bcc.length;
    if (totalRcpts == 0) {
        throw new MessagingException("No recipients to send to.");
    }

    MimeMessage mimeMsg = new MimeMessage(session);
    mimeMsg.setFrom(from);
    mimeMsg.setReplyTo(replyTo);
    mimeMsg.setRecipients(RecipientType.TO, to);
    mimeMsg.setRecipients(RecipientType.CC, cc);
    mimeMsg.setRecipients(RecipientType.BCC, bcc);

    // add in any additional headers
    Map<String, String> headers = email.getHeaders();
    if (headers != null && !headers.isEmpty()) {
        for (Entry<String, String> header : headers.entrySet()) {
            mimeMsg.setHeader(header.getKey(), header.getValue());
        }
    }

    // add the content to the message
    List<Message> parts = email.getParts();
    if (parts == null || parts.size() == 0) {
        setContent(mimeMsg, email);
    } else {
        // create a multipart container
        Multipart multipart = new MimeMultipart();

        // create a body part for the message text
        MimeBodyPart msgBodyPart = new MimeBodyPart();
        setContent(msgBodyPart, email);

        // add the message part to the container
        multipart.addBodyPart(msgBodyPart);

        // add attachments
        for (Message part : parts) {
            addPart(multipart, part);
        }

        // set the multipart container as the content of the message
        mimeMsg.setContent(multipart);
    }

    if (allowTransport) {
        // send
        Transport.send(mimeMsg);
    } else {
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            mimeMsg.writeTo(output);
            String emailString = output.toString();
            LOG.info(emailString);
            observable.notifyObservers(emailString);
        } catch (IOException e) {
            LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e);
        }
    }
}

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

/**
 * @see com.ess.messages.MailSender#send()
 *//*from w  w  w.j  a  v  a2  s.  c om*/
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:org.overlord.sramp.governance.services.NotificationResourceTest.java

@Test
public void testMail() {
    try {/*  ww  w  .  java 2 s.  co m*/
        mailServer = SimpleSmtpServer.start(smtpPort);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
        properties.setProperty("mail.smtp.port", String.valueOf(smtpPort)); //$NON-NLS-1$
        Session mailSession = Session.getDefaultInstance(properties);
        MimeMessage m = new MimeMessage(mailSession);
        Address from = new InternetAddress("me@gmail.com"); //$NON-NLS-1$
        Address[] to = new InternetAddress[1];
        to[0] = new InternetAddress("dev@mailinator.com"); //$NON-NLS-1$
        m.setFrom(from);
        m.setRecipients(Message.RecipientType.TO, to);
        m.setSubject("test"); //$NON-NLS-1$
        m.setContent("test", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
        Transport.send(m);

        Assert.assertTrue(mailServer.getReceivedEmailSize() > 0);
        @SuppressWarnings("rawtypes")
        Iterator iter = mailServer.getReceivedEmail();
        while (iter.hasNext()) {
            SmtpMessage email = (SmtpMessage) iter.next();
            System.out.println(email.getBody());
            Assert.assertEquals("test", email.getBody()); //$NON-NLS-1$
        }

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        mailServer.stop();
    }

}