Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

In this page you can find the example usage for javax.mail Transport send.

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

From source file:sk.mlp.security.EmailSender.java

/**
 * Metda sendUserPasswordRecoveryEmail je ur?en na generovbanie a zaslanie pouvateovi email s obnovenm jeho zabudnutho hesla.
 * @param email - pouvatesk email//from w  w  w. j a v  a 2 s  . com
 */
public void sendUserPasswordRecoveryEmail(String email) {
    try {
        DatabaseServices databaseServices = new DatabaseServices();
        User user = databaseServices.findUserByEmail(email);
        String name = "NONE";
        String surname = "NONE";
        if (user.getFirstName() != null) {
            name = user.getFirstName();
        }
        if (user.getLastName() != null) {
            surname = user.getLastName();
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", server);
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Your password to GPSWebApp server!!!");
            //message.setText(userToken);
            message.setSubject("Your password to GPSWebApp server!!!");
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname + ",</h1><br>your paassword to access GPSWebApp server is <b>" + user.getPass()
                    + "</b>. <br>Please take note that you can change it in your settings. Have a pleasant day.</body></html>",
                    "text/html");

            Transport.send(message);

            FileLogger.getInstance()
                    .createNewLog("Successfuly sent password recovery email to user " + email + ".");

        } catch (MessagingException e) {
            FileLogger.getInstance()
                    .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
        }
    } catch (Exception ex) {
        FileLogger.getInstance()
                .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
    }
}

From source file:webreader.WebReader.java

private void sendEmail(String inputMessage) {
    //---User login information
    final String username = email;
    final String password = emailPassword;

    //---Sets server for gmail
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    //---Creates a new session
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);

        }/*from   w  w w. java  2  s  . co  m*/

    });
    //---Try catch loop for sending an email
    //---Sends error email to the sender if catch is engaged.
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject("Your grades have been updated");
        message.setText(inputMessage);
        Transport.send(message);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        emailSent = "E-mail was sent: " + dateFormat.format(date);
        System.out.println(emailSent);
    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //---Used code from https://www.youtube.com/watch?v=sHC8YgW21ho
    //---for the above method
}

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

public void send() throws MessagingException {
    notNull(from, "From address can not be null");
    isTrue(!to.isEmpty() || !bcc.isEmpty(), "No TO or BCC addresses specified");

    MimeMessage message = getMessasge();

    // Cover wrap
    MimeBodyPart wrap = new MimeBodyPart();
    MimeMultipart cover = getCoverPart();
    wrap.setContent(cover);// w w w. ja  v a  2s. c  om

    MimeMultipart content = new MimeMultipart("related");
    message.setContent(content);
    content.addBodyPart(wrap);

    addAttachments(content);

    Transport.send(message);
}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/*from www .  j a  v a 2  s.  c o  m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override/*from ww w  .ja  v  a 2 s. c om*/
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

From source file:com.meg7.emailer.EmailerManager.java

private void sendMessages(List<Message> messages) {
    resetProgress(mContext);/*from   www.j av  a2s .  c  o m*/

    int position = 0;
    int count = messages.size();
    for (Message message : messages) {
        position += 1;

        try {
            Transport.send(message);

            ProgressPreferenceUtils.incrementSentCount(mContext);
        } catch (Exception e) {
            ProgressPreferenceUtils.incrementFailedCount(mContext);

            MLog.e(TAG, e.toString());
        }

        ProgressPreferenceUtils.setProgressPercentage(mContext, position * 100 / count);

        if (!TaskerHelper.isTaskerRunning(mContext)) {
            resetProgress(mContext);
            return;
        }

        LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(Constants.ACTION_PROGRESS));
    }
}

From source file:org.eclipse.ecr.automation.core.mail.Mailer.java

/**
 * Send a single email.//from   w  w  w .ja va  2  s.  c o  m
 */
public void sendEmail(String from, String to, String subject, String body) throws MessagingException {
    // Here, no Authenticator argument is used (it is null).
    // Authenticators are used to prompt the user for user
    // name and password.
    MimeMessage message = new MimeMessage(getSession());
    // the "from" address may be set in code, or set in the
    // config file under "mail.from" ; here, the latter style is used
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    Transport.send(message);
}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * POST to email a notification about an artifact.
 *
 * @param environment/*from  w ww  .j  a  va2 s . c o  m*/
 * @param uuid
 * @throws SrampAtomException
 */
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces("application/xml")
public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request,
        @PathParam("group") String group, @PathParam("template") String template,
        @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception {

    Map<String, ValueEntity> results = new HashMap<String, ValueEntity>();
    try {
        // 0. run the decoder on the arguments, after replacing * by % (this so parameters can
        //    contain slashes (%2F)
        group = SlashDecoder.decode(group);
        template = SlashDecoder.decode(template);
        target = SlashDecoder.decode(target);
        uuid = SlashDecoder.decode(uuid);

        // 1. get the artifact from the repo
        SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
        QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$
        if (queryResultSet.size() == 0) {
            results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
            results.put(GovernanceConstants.MESSAGE,
                    new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$
            return results;
        }
        ArtifactSummary artifactSummary = queryResultSet.iterator().next();

        // 2. get the destinations for this group
        NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
        if (destinations == null) {
            destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(),
                    group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
        }

        // 3. send the email notification
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress(destinations.getFromAddress());
            Address[] to = new InternetAddress[destinations.getToAddresses().length];
            for (int i = 0; i < destinations.getToAddresses().length; i++) {
                to[i] = new InternetAddress(destinations.getToAddresses()[i]);
            }
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);

            String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
            if (subjectUrl != null)
                subject = IOUtils.toString(subjectUrl);
            subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            m.setSubject(subject);

            m.setSentDate(new java.util.Date());
            String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL contentUrl = Governance.class.getClassLoader().getResource(content);
            if (contentUrl != null)
                content = IOUtils.toString(contentUrl);
            content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
            m.setContent(content, "text/plain"); //$NON-NLS-1$
            Transport.send(m);
        } catch (javax.mail.MessagingException e) {
            logger.error(e.getMessage(), e);
        }

        // 4. build the response
        results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$

        return results;
    } catch (Exception e) {
        logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
        throw new SrampAtomException(e);
    }
}

From source file:com.esri.gpt.framework.mail.MailRequest.java

/**
 * Sends the E-Mail message.//from   w  w w .java2  s. com
 * @throws AddressException if an E-Mail address is invalid
 * @throws MessagingException if an exception occurs
 */
public void send() throws AddressException, MessagingException {

    // setup the mail server properties
    Properties props = new Properties();
    props.put("mail.smtp.host", getHost());
    if (getPort() > 0) {
        props.put("mail.smtp.port", "" + getPort());
    }

    // set up the message
    Session session = Session.getDefaultInstance(props, _authenticator);
    Message message = new MimeMessage(session);
    message.setSubject(getSubject());
    message.setContent(getBody(), getMimeType());
    message.setFrom(makeAddress(escapeHtml4(stripControls(getFromAddress()))));
    for (String sTo : getRecipients()) {
        message.addRecipient(Message.RecipientType.TO, makeAddress(sTo));
    }

    // send the message
    Transport.send(message);
}

From source file:com.fiveamsolutions.nci.commons.util.MailUtils.java

/**
 * Send an email./*  w  w  w  .j a  v a2s  . co m*/
 * @param u the recipient of the message
 * @param title the subject of the message
 * @param html the html content of the message
 * @param plainText the plain text content of the message
 * @throws MessagingException on error.
 */
public static void sendEmail(AbstractUser u, String title, String html, String plainText)
        throws MessagingException {
    if (!isMailEnabled()) {
        LOG.info("sending email to " + u.getEmail() + " with title " + title);
        LOG.info("plain text: " + plainText);
        LOG.info("html: " + html);
        return;
    }
    MimeMessage msg = new MimeMessage(getMailSession());
    msg.setFrom(new InternetAddress(getFromAddress()));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));
    msg.setSubject(title);
    Multipart mp = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(html, "text/html");
    mp.addBodyPart(bp);

    bp = new MimeBodyPart();
    bp.setContent(plainText, "text/plain");
    mp.addBodyPart(bp);

    msg.setContent(mp);

    Transport.send(msg);
}