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.codice.ddf.catalog.ui.query.monitor.email.EmailNotifier.java

private void sendEmailForWorkspace(WorkspaceMetacardImpl workspaceMetacard, Long hitCount, String email) {

    String emailBody = metacardFormatter.format(bodyTemplate, workspaceMetacard, hitCount);

    String subject = metacardFormatter.format(subjectTemplate, workspaceMetacard, hitCount);

    Session session = smtpClient.createSession();

    try {/*from w ww  . j a  v  a  2 s.com*/
        MimeMessage mimeMessage = new MimeMessage(session);

        mimeMessage.setFrom(new InternetAddress(fromEmail));

        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        mimeMessage.setSubject(subject);

        mimeMessage.setText(emailBody);

        LOGGER.trace("Attempting to send email");

        smtpClient.send(mimeMessage);

    } catch (MessagingException e) {
        LOGGER.warn("unable to send email to {}", email, e);
    }
}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;//from  w w w . j  a  v a 2s.c  o m
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:com.hiperium.bo.manager.mail.EmailMessageManager.java

/**
 * Sends an email with the new user password.
 * //from  w w  w  . j  a  v  a 2 s. c o  m
 * @param user
 * @throws javax.mail.internet.AddressException
 * @throws javax.mail.MessagingException
 */
public void sendNewPassword(User user) {
    try {
        this.log.debug("sendNewPassword() - START");
        // Create the corresponding user locale.
        Locale locale = null;
        if (StringUtils.isBlank(user.getLanguageId())) {
            locale = Locale.getDefault();
        } else {
            locale = new Locale(user.getLanguageId());
        }
        ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale);

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", CloudEmailUser.HOST);
        properties.setProperty("mail.user", CloudEmailUser.USERNAME);
        properties.setProperty("mail.password", CloudEmailUser.PASSWORD);
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS));
        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
        // Set Subject: header field
        message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT));
        // Send the actual HTML message, as big as you like
        message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT),
                user.getFirstname(), user.getLastname(), user.getPassword()), "text/html");
        // Send message
        Transport.send(message);
        this.log.debug("sendNewPassword() - END");
    } catch (AddressException e) {
        this.log.error("AddressException to send email to " + user.getEmail(), e);
    } catch (MessagingException e) {
        this.log.error("MessagingException to send email to " + user.getEmail(), e);
    }
}

From source file:gov.nih.nci.cabig.caaers.web.admin.DiagnosticsController.java

private boolean testSmtp(DiagnosticsCommand diagnosticsCommand) {
    boolean testResult = false;
    try {/* ww w . j av  a 2s  .  co m*/
        MimeMessage message = caaersJavaMailSender.createMimeMessage();
        message.setSubject("Test mail from caAERS Diagnostics");
        message.setFrom(new InternetAddress("caaers.app@gmail.com"));

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        String fromEmail = configuration.get(Configuration.SYSTEM_FROM_EMAIL);
        if (fromEmail == null)
            fromEmail = "admin@semanticbits.com";
        helper.setTo(fromEmail);
        caaersJavaMailSender.send(message);
        testResult = true;
    } catch (Exception e) {
        //log.error(" Error in sending email , please check the confiuration " + e);
        diagnosticsCommand.setSmtpException(e);
        testResult = false;
    }
    return testResult;
}

From source file:org.b3log.solo.mail.local.MailSender.java

/**
 * Converts the specified message into a {@link javax.mail.Message
 * javax.mail.Message}.//  w w  w.j a  va  2  s . c o m
 *
 * @param message the specified message
 * @return a {@link javax.mail.internet.MimeMessage}
 * @throws Exception if converts error
 */
public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception {
    if (null == message) {
        return null;
    }

    if (StringUtils.isBlank(message.getFrom())) {
        throw new MessagingException("Null from");
    }

    if (null == message.getRecipients() || message.getRecipients().isEmpty()) {
        throw new MessagingException("Null recipients");
    }

    final MimeMessage ret = new MimeMessage(getSession());

    ret.setFrom(new InternetAddress(message.getFrom()));
    final String subject = message.getSubject();

    ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B"));
    final String htmlBody = message.getHtmlBody();

    ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8");
    ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients()));

    return ret;
}

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();/*from w  ww. j a  v a  2  s .c o  m*/

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.tomitribe.tribestream.registryng.service.monitoring.MailAlerter.java

private void sendMail(final Alert alert) throws MessagingException {
    final String subject = StrSubstitutor.replace(subjectTemplate, new HashMap<String, String>() {
        {/*from  w w  w . ja va  2 s .co m*/
            put("hostname", hostname);
            put("date", LocalDateTime.now().toString());
        }
    });
    final String body = alert.text();

    final MimeMessage message = new MimeMessage(session);
    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:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java

/**
 * ??//from   w w w.j  ava 2s  .c o  m
 * @param originator 
 * @param recipients ?
 * @param subject ??
 * @return 
 * @throws EnterpriseException ?
 */
private Message createMessage(final InternetAddress originator,
        final Map<RecipientType, InternetAddress> recipients, final String subject) throws EnterpriseException {
    Validate.isTrue(recipients.size() > 0);
    try {
        final MimeMessage message = new MimeMessage(session);
        if (originator != null) {
            message.setFrom(originator);
        }
        for (final Entry<RecipientType, InternetAddress> recipient : recipients.entrySet()) {
            message.addRecipient(recipient.getKey(), recipient.getValue());
        }
        message.setSubject(subject, CHARSET);
        return message;
    } catch (final MessagingException e) {
        throw new EnterpriseException(e);
    }
}

From source file:com.github.sleroy.junit.mail.server.test.MailSender.java

/**
 * Send mail./*from  w  w w  .  j  a v a  2 s .c o  m*/
 *
 * @param from
 *            Sender's email ID needs to be mentioned
 * @param to
 *            Recipient's email ID needs to be mentioned.
 * @param subject
 *            the subject
 * @throws MessagingException
 */
public void sendMail(String from, String to, String subject, String body) throws MessagingException {

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.port", Integer.toString(port));

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    Transport transport = null;
    try {
        transport = session.getTransport();

        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(body);

        // Send message
        transport.send(message);
        System.out.println("Sent message successfully....");
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java

@Test
public void testStartTLSWithJavamail() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/* ww  w .j  a va 2  s.  c  o m*/
    try {
        TestMessageHook hook = new TestMessageHook();
        server = createServer(createProtocol(hook), address,
                Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
        server.bind();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", address.getHostName());
        mailProps.put("mail.smtp.port", address.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);

        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        String[] emails = { "valid@localhost" };
        Address rcpts[] = new Address[emails.length];
        for (int i = 0; i < emails.length; i++) {
            rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase());
        }
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

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

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

        assertEquals(1, hook.getQueued().size());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}