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:bean.RedSocial.java

/**
 * //from  w w w .j  a  v  a  2 s.c  o  m
 * @param _username
 * @param _email
 * @param _password 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class)
public void solicitarAcceso(String _username, String _email, String _password) {
    if (daoUsuario.obtenerUsuario(_username) != null) {
        throw new exceptionsBusiness.UsernameNoDisponible();
    }

    String hash = BCrypt.hashpw(_password, BCrypt.gensalt());

    Token token = new Token(_username, _email, hash);
    daoToken.guardarToken(token);

    //enviar token de acceso a la direccion email

    String correoEnvia = "skala2climbing@gmail.com";
    String claveCorreo = "vNspLa5H";

    // La configuracin para enviar correo
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.user", correoEnvia);
    properties.put("mail.password", claveCorreo);

    // Obtener la sesion
    Session session = Session.getInstance(properties, null);

    try {
        // Crear el cuerpo del mensaje
        MimeMessage mimeMessage = new MimeMessage(session);

        // Agregar quien enva el correo
        mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing"));

        // Los destinatarios
        InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) };

        // Agregar los destinatarios al mensaje
        mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);

        // Agregar el asunto al correo
        mimeMessage.setSubject("Confirmacin de registro");

        // Creo la parte del mensaje
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        String ip = "90.165.24.228";
        mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip
                + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token="
                + token.getToken());
        //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible");

        // Crear el multipart para agregar la parte del mensaje anterior
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        // Agregar el multipart al cuerpo del mensaje
        mimeMessage.setContent(multipart);

        // Enviar el mensaje
        Transport transport = session.getTransport("smtp");
        transport.connect(correoEnvia, claveCorreo);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();

    } catch (UnsupportedEncodingException | MessagingException ex) {
        throw new ErrorEnvioEmail();
    }

}

From source file:io.mapzone.arena.share.app.EMailSharelet.java

private void sendEmail(final String toText, final String subjectText, final String messageText,
        final boolean withAttachment, final ImagePngContent image) throws Exception {
    MimeMessage msg = new MimeMessage(mailSession());

    msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false));
    // TODO we need the FROM from the current user
    msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );
    msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );

    msg.setSubject(subjectText, "utf-8");
    if (withAttachment) {
        // add mime multiparts
        Multipart multipart = new MimeMultipart();

        BodyPart part = new MimeBodyPart();
        part.setText(messageText);//  w w  w  . java2  s . co m
        multipart.addBodyPart(part);

        // Second part is attachment
        part = new MimeBodyPart();
        part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource))));
        part.setFileName("preview.png");
        part.setHeader("Content-ID", "preview");
        multipart.addBodyPart(part);

        // // third part in HTML with embedded image
        // part = new MimeBodyPart();
        // part.setContent( "<img src='cid:preview'>", "text/html" );
        // multipart.addBodyPart( part );

        msg.setContent(multipart);
    } else {
        msg.setText(messageText, "utf-8");
    }
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:bioLockJ.module.agent.MailAgent.java

private Message getMimeMessage() throws Exception {
    final Message message = new MimeMessage(getSession());
    message.setFrom(new InternetAddress(emailFrom));
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getRecipients()));
    message.setSubject("BioLockJ " + Config.requireString(Config.PROJECT_NAME) + " " + status);
    message.setContent(getContent());/*from  ww w . j av  a 2  s .c o m*/
    return message;
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//from  w w  w  . j  ava2s.  c  o m
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmail(String to, String from, String subject, String bodyText)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

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

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailSimpleText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);

    MessageListener mockListener2 = mock(MessageListener.class);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);/*from w  w  w. j  a v  a 2 s . c  om*/
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Simple text Email test", message.getTitle());
    assertEquals(textEmailContent, message.getBody());
    assertEquals(textEmailContent.substring(0, 200), message.getSummary());
    assertEquals(0, message.getAttachmentsSize());
    assertEquals(0, message.getAttachments().size());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/plain; charset=" + System.getProperty("file.encoding"), message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format)./*from  w  w w.j  ava 2s. c  om*/
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:ee.cyber.licensing.service.MailService.java

public void sendExpirationNearingMail(License license) throws IOException, MessagingException {
    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");
    final String mailTo = mailServerProperties.getProperty("mailTo");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//  www  .j a va2s.  c om
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "Licensing service"));
    mailMessage.setSubject("License with id " + license.getId() + " is expiring");
    mailMessage.setSentDate(new Date());
    mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    String emailBody = "This is test<br><br> Regards, <br>Licensing team";
    mailMessage.setContent(emailBody, "text/html");

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);

}

From source file:com.app.mail.DefaultMailSender.java

private Message _populateMessage(String emailAddress, String subject, String template, Session session)
        throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert"));

    message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));

    message.setSubject(subject);/*from ww  w.ja  v a 2s  .co m*/

    Map<String, Object> rootMap = new HashMap<>();

    rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME);

    String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/" + template,
            "UTF-8", rootMap);

    message.setContent(messageBody, "text/html");

    return message;
}

From source file:davmail.smtp.TestSmtp.java

public void testSendMessageTwice() throws IOException, MessagingException, InterruptedException {
    Settings.setProperty("davmail.smtpCheckDuplicates", "true");
    String body = "First line\r\n.\r\nSecond line";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("to", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body);//from   w  ww . ja v  a 2  s. c  o  m
    sendAndCheckMessage(mimeMessage);
    sendAndCheckMessage(mimeMessage);
}

From source file:com.netspective.commons.message.SendMail.java

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }/*from  w w  w.j ava 2  s .  c  om*/
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}