Example usage for javax.mail.internet MimeMessage setSubject

List of usage examples for javax.mail.internet MimeMessage setSubject

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setSubject.

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:com.otz.plugins.transport.aws.ses.SpringEmailSender.java

public void send(String templateName, Locale locale, String to, Map<String, String> parameters)
        throws MessagingException {

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(emailTemplateRepository.getFrom(templateName, locale)));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(emailTemplateRepository.getSubject(templateName, locale));
    msg.setContent(emailTemplateRepository.getContent(templateName, locale, parameters),
            emailTemplateRepository.getContentType(templateName, locale));

    try {// w w  w .j a v  a  2 s  .  c  o  m
        // Create a transport.
        transport = session.getTransport();
        transport.connect(emailConfigParameters.getHost(), emailConfigParameters.getAccessKey(),
                emailConfigParameters.getSecretKey());
        transport.sendMessage(msg, msg.getAllRecipients());

    } catch (Exception e) {

        // TODO deal with failure to send
        // send message to hipchat
        e.printStackTrace();
    }

}

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {/* ww w.j av a 2s. c  o m*/
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:org.apache.camel.component.google.mail.GmailUsersMessagesIntegrationTest.java

private Message createTestEmail() throws MessagingException, IOException {
    com.google.api.services.gmail.model.Profile profile = requestBody(
            "google-mail://users/getProfile?inBody=userId", CURRENT_USERID);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject("Hello from camel-google-mail");
    mm.setContent("Camel rocks!", "text/plain");
    Message createMessageWithEmail = createMessageWithEmail(mm);
    return createMessageWithEmail;
}

From source file:org.lf.yydp.service.film.BuyTicketService.java

/**
 * :?/*ww  w.  j a v a2 s.  c  o m*/
 * @param receiver
 */
public void sendEmail(String receiver) {
    Properties p = null;
    InputStream inputSteam = null;
    String senter = null;
    String Subject = null;
    String Content = null;
    try {
        p = new Properties();
        inputSteam = BuyTicketService.class.getClassLoader().getResourceAsStream("mail.properties");
        p.load(inputSteam);
        final String uname = p.getProperty("mail.uname");
        final String license = p.getProperty("mail.license");
        senter = p.getProperty("mail.senter");
        Subject = p.getProperty("mail.subject");
        Content = p.getProperty("mail.content");
        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uname, license);
            }
        };
        Session session = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senter));
        msg.setRecipient(RecipientType.TO, new InternetAddress(receiver));
        msg.setSubject(Subject);
        msg.setContent(Content, "text/html;charset=utf-8");
        Transport.send(msg);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputSteam != null) {
                inputSteam.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }
}

From source file:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it./*from   ww w.  j ava2  s  . c o  m*/
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}

From source file:ru.org.linux.util.EmailService.java

public void sendEmail(String nick, String email, boolean isNew) throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {//from w  w w .  ja v  a 2  s.c  o  m
        text.append(
                "\t?   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t?   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(configuration.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}

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 av  a 2s . c om
 *
 * @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:org.wandora.piccolo.actions.SendEmail.java

public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response,
        Application application) {//from  w  w w .j  a  v  a 2 s  .  c o m
    try {

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        if (subject != null)
            message.setSubject(subject);
        if (from != null)
            message.setFrom(new InternetAddress(from));
        Vector<String> recipients = new Vector<String>();
        if (recipient != null) {
            String[] rs = recipient.split(",");
            String r = null;
            for (int i = 0; i < rs.length; i++) {
                r = rs[i];
                if (r != null)
                    recipients.add(r);
            }
        }

        MimeMultipart multipart = new MimeMultipart();

        Template template = application.getTemplate(emailTemplate, user);
        HashMap context = new HashMap();
        context.put("request", request);
        context.put("message", message);
        context.put("recipients", recipients);
        context.put("emailhelper", new MailHelper());
        context.put("multipart", multipart);
        context.putAll(application.getDefaultContext(user));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        template.process(context, baos);

        MimeBodyPart mimeBody = new MimeBodyPart();
        mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType());
        //            mimeBody.setContent(baos.toByteArray(),template.getMimeType());
        multipart.addBodyPart(mimeBody);
        message.setContent(multipart);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpServer, smtpUser, smtpPass);
        Address[] recipientAddresses = new Address[recipients.size()];
        for (int i = 0; i < recipientAddresses.length; i++) {
            recipientAddresses[i] = new InternetAddress(recipients.elementAt(i));
        }
        transport.sendMessage(message, recipientAddresses);
    } catch (Exception e) {
        logger.writelog("WRN", e);
    }
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {//from  w  w  w . j a  va2s.  co  m
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:com.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection.//  www .j av a 2  s . c o m
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}