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:com.intranet.intr.proveedores.EmpControllerGestion.java

public void enviarProvUC(proveedores proveedor) {
    String cuerpo = "";
    String servidorSMTP = "smtp.1and1.es";
    String puertoEnvio = "465";
    Properties props = new Properties();//propiedades a agragar
    props.put("mail.smtp.user", miCorreo);//correo origen
    props.put("mail.smtp.host", servidorSMTP);//tipo de servidor
    props.put("mail.smtp.port", puertoEnvio);//puesto de salida
    props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor
    props.put("mail.smtp.auth", "true");//autentificacion
    props.put("mail.smtp.password", "angel2010");//autentificacion
    props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SecurityManager security = System.getSecurityManager();

    Authenticator auth = new autentificadorSMTP();//autentificar el correo
    Session session = Session.getInstance(props, auth);//se inica una session
    // session.setDebug(true);

    try {// ww w  .jav  a  2 s .  co  m
        // Creamos un objeto mensaje tipo MimeMessage por defecto.
        MimeMessage mensajeE = new MimeMessage(session);

        // Asignamos el de o from? al header del correo.
        mensajeE.setFrom(new InternetAddress(miCorreo));

        // Asignamos el para o to? al header del correo.
        mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail()));

        // Asignamos el asunto
        mensajeE.setSubject("Su Perfil Personal");

        // Creamos un cuerpo del correo con ayuda de la clase BodyPart
        //BodyPart cuerpoMensaje = new MimeBodyPart();

        // Asignamos el texto del correo
        String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: "
                + proveedor.getContrasenna()
                + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm";
        // Asignamos el texto del correo
        cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>";
        mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>", "text/html");
        //mensaje.setText(text);

        // Creamos un multipart al correo

        // Enviamos el correo
        Transport.send(mensajeE);
        System.out.println("Mensaje enviado");

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }/*  w w w  . java 2s .  co m*/
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email/* w  ww  . j  a v  a 2  s  . c  om*/
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    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);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {//from ww  w  .ja  va2 s.c  o  m
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

protected void generateMail(String destination, String copy, String title, String content)
        throws NamingException, MessagingException {

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(getJavaMailJndiName());

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false));
    if (!isBlank(copy)) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false));
    }//from w  ww  .j a  va  2 s  .  c o m

    msg.setSubject(title, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content, "text/html; charset=utf-8");

    Transport.send(msg);
}

From source file:org.apache.james.mailetcontainer.impl.JamesMailetContext.java

/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition// w ww.  j av  a 2 s .  c om
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    // This sends a message to the james component that is a bounce of the
    // sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = new HashSet<MailAddress>();
    recipients.add(mail.getSender());
    InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) };
    reply.setRecipients(Message.RecipientType.TO, addr);
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return new MailImpl("replyTo-" + mail.getName(),
            new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply);
}

From source file:org.snopoke.util.Emailer.java

/**
 * Create the MimeMessage and set the to/from/subject
 * //from w w  w.  j  a  v a  2  s  .  c o m
 * @return MimeMessaeg
 * @throws MessagingException
 */
private MimeMessage getMessasge() throws MessagingException {
    MimeMessage message = new MimeMessage(getSession());
    message.setSentDate(new Date());

    for (Address toAddress : to) {
        message.addRecipient(RecipientType.TO, toAddress.getInternetAddress());
    }

    for (Address toAddress : cc) {
        message.addRecipient(RecipientType.CC, toAddress.getInternetAddress());
    }

    for (Address toAddress : bcc) {
        message.addRecipient(RecipientType.BCC, toAddress.getInternetAddress());
    }

    message.setFrom(from.getInternetAddress());

    if (subject != null && !subject.isEmpty())
        message.setSubject(subject, "UTF-8");
    return message;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail
 * /*w  w w  . ja  v  a  2 s.co  m*/
 * @param mail The original Mail object
 * @param session Mail session
 * @return The MIME message
 */
private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context)
        throws MessagingException, XWikiException, IOException {
    // this will also check for email error
    InternetAddress from = new InternetAddress(mail.getFrom());
    String recipients = mail.getHeader("To");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getTo();
    } else {
        recipients = mail.getTo() + "," + recipients;
    }
    InternetAddress[] to = toInternetAddresses(recipients);
    recipients = mail.getHeader("Cc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getCc();
    } else {
        recipients = mail.getCc() + "," + recipients;
    }
    InternetAddress[] cc = toInternetAddresses(recipients);
    recipients = mail.getHeader("Bcc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getBcc();
    } else {
        recipients = mail.getBcc() + "," + recipients;
    }
    InternetAddress[] bcc = toInternetAddresses(recipients);

    if ((to == null) && (cc == null) && (bcc == null)) {
        LOGGER.info("No recipient -> skipping this email");
        return null;
    }

    MimeMessage message = new MimeMessage(session);
    message.setSentDate(new Date());
    message.setFrom(from);

    if (to != null) {
        message.setRecipients(javax.mail.Message.RecipientType.TO, to);
    }

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

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

    message.setSubject(mail.getSubject(), EMAIL_ENCODING);

    for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) {
        message.setHeader(header.getKey(), header.getValue());
    }

    if (mail.getHtmlPart() != null || mail.getAttachments() != null) {
        Multipart multipart = createMimeMultipart(mail, context);
        message.setContent(multipart);
    } else {
        message.setText(mail.getTextPart());
    }

    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}

From source file:org.tsm.concharto.web.feedback.FeedbackController.java

public MimeMessage makeFeedbackMessage(MimeMessage message, FeedbackForm feedbackForm,
        HttpServletRequest request) {/*w  ww .j  a  v  a  2 s .  c  o  m*/

    //prepare the user info
    String requestInfo = getBrowserInfo(request);

    StringBuffer messageText = new StringBuffer(feedbackForm.getBody())
            .append("\n\n=============================================================\n").append(requestInfo);

    InternetAddress from = new InternetAddress();
    from.setAddress(feedbackForm.getEmail());
    InternetAddress to = new InternetAddress();
    to.setAddress(sendFeedbackToAddress);
    try {
        from.setPersonal(feedbackForm.getName());
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(FEEDBACK_SUBJECT + feedbackForm.getSubject());
        message.setText(messageText.toString());
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);/*from  w w w. java 2  s. co  m*/
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}