List of usage examples for javax.mail.internet MimeMessage setText
@Override public void setText(String text) throws MessagingException
From source file:org.grouter.common.mail.MailHandler.java
/** * Creates a multipart email with html and plain text email body to fallback to if * email client do not handle html base emails. * * @param mimeMessage/*from w ww. j a v a 2s . c om*/ * @param dto * @throws MessagingException */ private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException { if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) { mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE); // Create your text message part BodyPart plainBodyPart = new MimeBodyPart(); plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainBodyPart); StringBuilder sb = new StringBuilder(); sb.append(PRE_HTML_HEADER); sb.append(dto.getSubject()).append("\n"); sb.append(POST_HTML_HEADER); sb.append(dto.getHtmlTextBody()); sb.append(END_HTML); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML); // Add html part to multi part multipart.addBodyPart(htmlBodyPart); mimeMessage.setContent(multipart); } else { mimeMessage.setSubject(dto.getSubject()); mimeMessage.setText(dto.getPlainTextBody()); mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); } }
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 ww w. j a v a 2 s .co m } 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); }
From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java
/** * Check the properties file to figure out if an email needs to be sent at * the end of the job. If yes, get mail properties and try and send email * about Job Status./* ww w.j a v a2 s.c o m*/ * * @return 0 for success, -1 for failure * @throws GenieException on issue */ private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException { LOG.debug("called"); final Job job = this.jobService.getJob(this.jobId); if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) { LOG.warn("Email is disabled but user has specified an email address."); return false; } // Sender's email ID final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com"); LOG.info("From email address to use to send email: " + fromEmail); // Set the smtp server hostname. Use localhost as default final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost"); LOG.debug("Email smtp server: " + smtpHost); // Get system properties final Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); // check whether authentication should be turned on Authenticator auth = null; if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) { LOG.debug("Email Authentication Enabled"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); final String userName = config.getString("com.netflix.genie.server.mail.smtp.user"); final String password = config.getString("com.netflix.genie.server.mail.smtp.password"); if (userName == null || password == null) { LOG.error("Authentication is enabled and username/password for smtp server is null"); return false; } LOG.debug("Constructing authenticator object with username" + userName + " and password " + password); auth = new SMTPAuthenticator(userName, password); } else { LOG.debug("Email authentication not enabled."); } // Get the default Session object. final Session session = Session.getInstance(properties, auth); try { // Create a default MimeMessage object. final MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(fromEmail)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); JobStatus jobStatus; if (killed) { jobStatus = JobStatus.KILLED; } else { jobStatus = job.getStatus(); } // Set Subject: header field message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus); // Now set the actual message final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: " + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: " + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n"; message.setText(body); // Send message Transport.send(message); LOG.info("Sent email message successfully...."); return true; } catch (final MessagingException mex) { LOG.error("Got exception while sending email", mex); return false; } }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * /*from w ww . j a v a2 s . c o m*/ * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(User toUser, GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Dear " + toUser.getFullName() + ", \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n"); builder.append("Please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (Exception e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:cz.incad.vdkcommon.solr.Indexer.java
private void sendDemandMail(SolrDocument resultDoc, String id) { try {//from w ww. j av a2 s .c o m String title = (String) resultDoc.getFieldValues("title").toArray()[0]; String pop = (String) resultDoc.getFieldValue("poptavka_ext"); JSONObject j = new JSONObject(pop); String from = opts.getString("admin.email"); Knihovna kn = new Knihovna(j.getString("knihovna")); String to = kn.getEmail(); String zaznam = j.optString("zaznam"); String code = j.optString("code"); String exemplar = j.optString("exemplar"); try { Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(opts.getString("admin.email.demand.subject")); String link = opts.getString("app.url") + "/original?id=" + id; String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title) .replace("${demand.url}", link); message.setText(body); Transport.send(message); LOGGER.fine("Sent message successfully...."); } catch (MessagingException ex) { LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from }); LOGGER.log(Level.SEVERE, null, ex); } } catch (NamingException | SQLException ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * Send an mail containing the error message back to the * user which sent the given message.//from w w w . j av a2 s . c o m * * @param m The message which produced an error while handling it. * @param error The error string. */ private void sendErrorMessage(Message m, String error) throws Exception { /* get the SMTP mail server */ SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer(); if (smtpMailServer == null) { log.warn("Failed to send error message as no SMTP server is configured"); return; } /* get system properties */ Properties props = System.getProperties(); /* Setup mail server */ props.put("mail.smtp.host", smtpMailServer.getHostname()); /* get a session */ Session session = Session.getDefaultInstance(props, null); /* create the message */ MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom())); String senderEmail = getEmailAddressFromMessage(m); if (senderEmail == "") { throw new Exception("Unknown sender of email."); } message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail)); message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")"); message.setText("An error occurred while handling your message:\n\n " + error + "\n\nPlease contact the administrator to solve the problem.\n"); /* send the message */ Transport tr = session.getTransport("smtp"); if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) { tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword()); } else { int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort()); tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(), smtpMailServer.getPassword()); } message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
From source file:net.naijatek.myalumni.util.mail.FreeMarkerTemplateMailerImpl.java
public void mail(final String email, final Map map, final String bodyTemplatePrefix, final String subjectTemplatePrefix) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); ///*w ww . j a v a 2 s . c om*/ // Get the subject // //BodyPart subjectPart = new MimeBodyPart(); Template subjectTextTemplate = configuration.getTemplate(subjectTemplatePrefix); final StringWriter subjectTextWriter = new StringWriter(); try { subjectTextTemplate.process(map, subjectTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Subject Text", e); } mimeMessage.setSubject(subjectTextWriter.toString()); // // Create a "text" Multipart message // Template bodyTextTemplate = configuration.getTemplate(bodyTemplatePrefix); final StringWriter bodyTextWriter = new StringWriter(); try { bodyTextTemplate.process(map, bodyTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Body Text", e); } mimeMessage.setText(bodyTextWriter.toString()); /* // @TODO - This part handles sending an attachement textPart.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(bodyTextWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/plain"; } public String getName() { return "main"; } })); mp.addBodyPart(textPart);*/ /* // Create a "HTML" Multipart message Multipart htmlContent = new MimeMultipart("related"); BodyPart htmlPage = new MimeBodyPart(); Template htmlTemplate = configuration.getTemplate(templatePrefix + "-html.ftl"); final StringWriter htmlWriter = new StringWriter(); try { htmlTemplate.process(map, htmlWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate HTML subscription mail", e); } htmlPage.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(htmlWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/html"; } public String getName() { return "main"; } })); htmlContent.addBodyPart(htmlPage); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent); mp.addBodyPart(htmlPart); mimeMessage.setContent(mp);*/ } }; mailSender.send(preparator); }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;//from www.j av a 2 s .co m } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java
@Test public void testCheckNewMessages() throws MessagingException, IOException { org.jvnet.mock_javamail.Mailbox.clearAll(); MessageChecker messageChecker = getMessageChecker(); messageChecker.removeListener("componentId"); messageChecker.removeListener("thesimpsons@silverpeas.com"); messageChecker.removeListener("theflanders@silverpeas.com"); StubMessageListener mockListener1 = new StubMessageListener("thesimpsons@silverpeas.com"); StubMessageListener mockListener2 = new StubMessageListener("theflanders@silverpeas.com"); messageChecker.addMessageListener(mockListener1); messageChecker.addMessageListener(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("Plain text Email test with attachment"); MimeBodyPart attachment = new MimeBodyPart( TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html")); attachment.setDisposition(Part.INLINE); attachment.setFileName("lemonde.html"); MimeBodyPart body = new MimeBodyPart(); body.setText(textEmailContent);//from w ww. ja v a 2 s . c o m Multipart multiPart = new MimeMultipart(); multiPart.addBodyPart(body); multiPart.addBodyPart(attachment); mail.setContent(multiPart); mail.setSentDate(new Date()); Date sentDate1 = new Date(mail.getSentDate().getTime()); Transport.send(mail); mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("bart.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Date sentDate2 = new Date(mail.getSentDate().getTime()); Transport.send(mail); //Unauthorized email mail = new MimeMessage(messageChecker.getMailSession()); bart = new InternetAddress("marge.simpson@silverpeas.com"); theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Plain text Email test"); mail.setText(textEmailContent); mail.setSentDate(new Date()); Transport.send(mail); assertThat(org.jvnet.mock_javamail.Mailbox.get("thesimpsons@silverpeas.com").size(), is(3)); messageChecker.checkNewMessages(new Date()); assertThat(mockListener2.getMessageEvent(), is(nullValue())); MessageEvent event = mockListener1.getMessageEvent(); assertThat(event, is(notNullValue())); assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages(), hasSize(2)); Message message = event.getMessages().get(0); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test with attachment")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getSentDate().getTime(), is(sentDate1.getTime())); assertThat(message.getAttachmentsSize(), greaterThan(0L)); assertThat(message.getAttachments(), hasSize(1)); String path = MessageFormat.format(theSimpsonsAttachmentPath, new Object[] { messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()) }); Attachment attached = message.getAttachments().iterator().next(); assertThat(attached.getPath(), is(path)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); message = event.getMessages().get(1); assertThat(message.getSender(), is("bart.simpson@silverpeas.com")); assertThat(message.getTitle(), is("Plain text Email test")); assertThat(message.getBody(), is(textEmailContent)); assertThat(message.getSummary(), is(textEmailContent.substring(0, 200))); assertThat(message.getAttachmentsSize(), is(0L)); assertThat(message.getAttachments(), hasSize(0)); assertThat(message.getComponentId(), is("thesimpsons@silverpeas.com")); assertThat(message.getSentDate().getTime(), is(sentDate2.getTime())); }
From source file:org.openbizview.util.Bvt002.java
/** * Enva notificacin a usuario al cambiar la contrasea **///from w w w. ja va2 s .c o m private void ChangePassNotification2(String mail, String clave) { try { Context initContext = new InitialContext(); Session session = (Session) initContext.lookup(JNDIMAIL); // Crear el mensaje a enviar MimeMessage mm = new MimeMessage(session); // Establecer las direcciones a las que ser enviado // el mensaje (test2@gmail.com y test3@gmail.com en copia // oculta) // mm.setFrom(new // InternetAddress("opennomina@dvconsultores.com")); mm.addRecipient(Message.RecipientType.TO, new InternetAddress(mail)); // Establecer el contenido del mensaje mm.setSubject(getMessage("mailUserUserChgPass")); mm.setText(getMessage("mailNewUserMsj2")); // use this is if you want to send html based message mm.setContent(getMessage("mailNewUserMsj6") + " " + coduser.toUpperCase() + " / " + clave + "<br/><br/> " + getMessage("mailNewUserMsj2"), "text/html; charset=utf-8"); // Enviar el correo electrnico Transport.send(mm); //System.out.println("Correo enviado exitosamente"); } catch (Exception e) { e.printStackTrace(); } }