List of usage examples for org.springframework.mail.javamail MimeMessageHelper setFrom
public void setFrom(String from) throws MessagingException
From source file:com.cerebro.provevaadin.smtp.ConfigurazioneSMTPSpring.java
public ConfigurazioneSMTPSpring() { TextField smtpHost = new TextField("SMTP Host Server"); smtpHost.setRequired(true);/*from w ww . j a va2 s. c om*/ TextField smtpPort = new TextField("SMTP Port"); smtpPort.setRequired(true); TextField smtpUser = new TextField("SMTP Username"); smtpUser.setRequired(true); PasswordField smtpPwd = new PasswordField("SMTP Password"); smtpPwd.setRequired(true); PasswordField pwdConf = new PasswordField("Conferma la Password"); pwdConf.setRequired(true); CheckBox security = new CheckBox("Sicurezza del server"); Properties props = new Properties(); InputStream config = VaadinServlet.getCurrent().getServletContext() .getResourceAsStream("/WEB-INF/config.properties"); if (config != null) { System.out.println("Carico file di configurazione"); try { props.load(config); } catch (IOException ex) { Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex); } } smtpHost.setValue(props.getProperty("mail.smtp.host")); smtpUser.setValue(props.getProperty("smtp_user")); security.setValue(Boolean.parseBoolean(props.getProperty("smtp_sec"))); Button salva = new Button("Salva i parametri"); salva.addClickListener((Button.ClickEvent event) -> { System.out.println("Salvo i parametri SMTP"); if (smtpHost.isValid() && smtpPort.isValid() && smtpUser.isValid() && smtpPwd.isValid() && smtpPwd.getValue().equals(pwdConf.getValue())) { System.out.println(smtpHost.getValue() + smtpPort.getValue() + smtpUser.getValue() + smtpPwd.getValue() + security.getValue().toString()); props.setProperty("mail.smtp.host", smtpHost.getValue()); props.setProperty("mail.smtp.port", smtpPort.getValue()); props.setProperty("smtp_user", smtpUser.getValue()); props.setProperty("smtp_pwd", smtpPwd.getValue()); props.setProperty("mail.smtp.ssl.enable", security.getValue().toString()); String webInfPath = VaadinServlet.getCurrent().getServletConfig().getServletContext() .getRealPath("WEB-INF"); File f = new File(webInfPath + "/config.properties"); try { OutputStream o = new FileOutputStream(f); try { props.store(o, "Prova"); } catch (IOException ex) { Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(ConfigurazioneSMTP.class.getName()).log(Level.SEVERE, null, ex); } Notification.show("Parametri salvati"); } else { Notification.show("Ricontrolla i parametri"); } }); TextField emailTest = new TextField("Destinatario Mail di Prova"); emailTest.setImmediate(true); emailTest.addValidator(new EmailValidator("Mail non valida")); Button test = new Button("Invia una mail di prova"); test.addClickListener((Button.ClickEvent event) -> { System.out.println("Invio della mail di prova"); if (emailTest.isValid() && !emailTest.isEmpty()) { System.out.println("Invio mail di prova a " + emailTest.getValue()); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setJavaMailProperties(props); mailSender.setUsername(props.getProperty("smtp_user")); mailSender.setPassword(props.getProperty("smtp_pwd")); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); try { helper.setFrom("dottmatteocasagrande@gmail.com"); helper.setSubject("Subject"); helper.setText("It works!"); helper.addTo(emailTest.getValue()); mailSender.send(message); } catch (MessagingException ex) { Logger.getLogger(ConfigurazioneSMTPSpring.class.getName()).log(Level.SEVERE, null, ex); } } else { Notification.show("Controlla l'indirizzo mail del destinatario"); } }); this.addComponents(smtpHost, smtpPort, smtpUser, smtpPwd, pwdConf, security, salva, emailTest, test); }
From source file:com.github.dactiv.common.spring.mail.JavaMailService.java
/** * ??/*w w w . j a v a2 s . c o m*/ * * @param sendTo ?? * @param sendFrom ? * @param subject * @param content * @param attachment mapkey????value????? */ private void doSend(String sendTo, String sendFrom, String subject, String content, Map<String, File> attachment) { try { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, encoding); helper.setTo(sendTo); helper.setFrom(sendFrom); helper.setSubject(subject); helper.setText(content, true); if (!MapUtils.isEmpty(attachment)) { for (Entry<String, File> entry : attachment.entrySet()) { helper.addAttachment(entry.getKey(), entry.getValue()); } } mailSender.send(msg); logger.info("???"); } catch (MessagingException e) { logger.error("", e); } catch (Exception e) { logger.error("??", e); } }
From source file:de.whs.poodle.services.EmailService.java
public void sendMail(Instructor from, String toUsername, List<String> bccUsernames, boolean senderBcc, String subject, String text, boolean setNoReply) throws MessagingException { if (bccUsernames == null) bccUsernames = new ArrayList<>(); if (toUsername == null && bccUsernames.isEmpty()) { log.info("sendMail(): no recipients, aborting."); return;/*from w w w . ja va 2 s. c om*/ } // may be empty if bccUsernames was not specified List<String> bccEmails = getEmailsForUsernames(bccUsernames); String fromEmail = getEmailForUsername(from.getUsername()); // create "from" as "FirstName LastName <email@w-hs.de>" String fromStr = String.format("%s %s <%s>", from.getFirstName(), from.getLastName(), fromEmail); if (senderBcc) bccEmails.add(fromEmail); // create MimeMessage MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8"); helper.setSubject("[Poodle] " + subject); helper.setFrom(fromStr); if (toUsername != null) { String toEmail = getEmailForUsername(toUsername); helper.setTo(toEmail); } if (!bccEmails.isEmpty()) helper.setBcc(bccEmails.toArray(new String[0])); if (setNoReply) helper.setReplyTo(poodle.getEmailNoReplyAddress()); helper.setText(text); mailSender.send(mimeMessage); }
From source file:com.freemarker.mail.GMail.java
public boolean SendMail(String To, String MessageContent, HttpServletRequest req) throws Exception { setMailsender();/*from www . j a v a2 s .com*/ String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateData(MessageContent, getTemplateLocation(req)); String From = "analytixdstest@gmail.com"; String Subject = "Freemarker Email Template"; MimeMessage mimeMessage = mailsender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8"); mimeMessage.setContent(FinalMessage, "text/html"); helper.setTo(To); helper.setSubject("Subject"); helper.setFrom(From); mailsender.send(mimeMessage); return true; }
From source file:com.indicator_engine.controller.RegistrationController.java
@RequestMapping(value = "/register", method = RequestMethod.POST) public String processRegistrationForm(@Valid @ModelAttribute("RegisterForm") RegistrationForm RegisterForm, BindingResult bindingResult, Map<String, Object> model) { if (bindingResult.hasErrors()) { return "app/register"; }//from w ww .ja va2s. c o m UserCredentialsDao userDetailsBean = (UserCredentialsDao) appContext.getBean("userDetails"); MimeMessage message = mailSender.createMimeMessage(); String errorMsg; String uname = RegisterForm.getUserName(); String password = RegisterForm.getPassword(); String hashedPassword = encoder.encode(password); Date dob = RegisterForm.getDob(); java.sql.Date sqlStartDate = null; sqlStartDate = new java.sql.Date(dob.getTime()); String email = RegisterForm.getEmail(); // Error Handling Not done Yet. Synchronize Java Script checks + Server Side checks. Eliminate redundant checks if (uname == null || email == null || password == null) errorMsg = "Error : Please Check your "; UserCredentials uc = new UserCredentials(uname, hashedPassword, new UserProfile(" ", " ", sqlStartDate, 0, " ", " ", " ", 0, " ", email)); userDetailsBean.add(uc); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("goalla@rwth-aachen.de"); helper.setTo(uc.getUp().getEmailid()); helper.setSubject("One Time Password for Verification"); /*Map<String, Object> modelMsg = new HashMap<String, Object>(); model.put("UserName", uc.getUname()); model.put("EmailID", uc.getUp().getEmailid()); model.put("DOB", uc.getUp().getDob()); model.put("OTP", uc.getOtp()); String emailText = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "registrationEmailTemplate.vm", "UTF-8", modelMsg); */ helper.setText("OTP For Verification : " + uc.getOtp()); /*FileSystemResource couponImage = new FileSystemResource("logo.png"); helper.addAttachment("logo.png", logoImage); ClassPathResource image = new ClassPathResource("rwth.png"); helper.addInline("UniLogo", image); */ } catch (javax.mail.MessagingException ex) { } mailSender.send(message); model.put("msg", uc.getUid()); return "app/registration_success"; }
From source file:com.gcrm.util.mail.MailService.java
public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames, File[] files) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;/*from ww w.java 2s. c om*/ if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } if (from == null) { from = emailSetting.getFrom_address(); } Session mailSession = createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); if (fileNames != null && files != null) { String fileName = null; File file = null; for (int i = 0; i < fileNames.length; i++) { fileName = fileNames[i]; file = files[i]; if (fileName != null && file != null) { helper.addAttachment(fileName, file); } } } transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:net.bafeimao.umbrella.web.test.MailTests.java
@Test public void testSendMailWithInlineImage() throws MessagingException { // ?,???html/*from w w w. j a va 2 s. c o m*/ MimeMessage mailMessage = senderImpl.createMimeMessage(); // ?boolean,?MimeMessageHelpertrue? // multipart? MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true); // messageHelper.setTo("29283212@qq.com"); messageHelper.setFrom("29283212@qq.com"); messageHelper.setSubject("!?"); // true ?HTML? messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>" + "<img src=\"cid:aaa\"/></body></html>", true); FileSystemResource img = new FileSystemResource(new File(imagePath)); messageHelper.addInline("aaa", img); // ?? senderImpl.send(mailMessage); System.out.println("???.."); }
From source file:com.globocom.grou.report.ReportService.java
private void notifyByMail(Test test, String email, Map<String, Double> result) throws Exception { MimeMessagePreparator messagePreparator = mimeMessage -> { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage); messageHelper.setTo(email);//from ww w .j av a 2 s.c o m messageHelper.setFrom(MAIL_FROM); messageHelper.setSubject(getSubject(test)); Context context = new Context(); context.setVariable("project", test.getProject()); context.setVariable("name", test.getName()); HashMap<String, Object> testContext = new HashMap<>(); testContext.put("dashboard", test.getDashboard()); testContext.put("loaders", test.getLoaders().stream().map(Loader::getName).collect(Collectors.toSet())); testContext.put("properties", test.getProperties()); testContext.put("id", test.getId()); testContext.put("created", test.getCreatedDate().toString()); testContext.put("lastModified", test.getLastModifiedDate().toString()); testContext.put("durationTimeMillis", test.getDurationTimeMillis()); context.setVariable("testContext", mapper.writeValueAsString(testContext).split("\\R")); Set<String> tags = test.getTags(); context.setVariable("tags", tags); context.setVariable("metrics", new TreeMap<>(result)); String content = templateEngine.process("reportEmail", context); messageHelper.setText(content, true); }; try { emailSender.send(messagePreparator); LOGGER.info( "Test " + test.getProject() + "." + test.getName() + ": sent notification to email " + email); } catch (MailException e) { LOGGER.error(e.getMessage(), e); } }
From source file:org.appverse.web.framework.backend.api.services.integration.impl.live.MailIntegrationServiceImpl.java
@Override @SuppressWarnings("unchecked") public void sendMail(String from, String[] to, String[] copyTo, String subject, String templateLocation, Map model) throws Exception { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to);//ww w.j ava2 s . c o m if (copyTo != null) { helper.setCc(copyTo); } helper.setSubject(subject); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, ENCODING, templateLocation, model); helper.setText(text, true); try { this.mailSender.send(message); } catch (MailSendException sendMailException) { Exception[] messageExceptions = sendMailException.getMessageExceptions(); for (Exception messageException : messageExceptions) { if (messageException instanceof SendFailedException) { SendFailedException sendFailedException = (SendFailedException) messageException; if (sendFailedException.getMessage().equals(INVALID_ADDRESSES)) { Address[] invalidAddresses = sendFailedException.getInvalidAddresses(); List<String> invalidAddressList = new ArrayList<String>(); for (Address invalidAddress : invalidAddresses) { String invalidAddressString = invalidAddress.toString(); invalidAddressList.add(invalidAddressString); } List<String> validToAdressesList = new ArrayList<String>(); if (to != null && to.length > 0) { for (String address : to) { if (!invalidAddressList.contains(address)) { validToAdressesList.add(address); } } } List<String> validCopyToAdressesList = new ArrayList<String>(); if (copyTo != null && copyTo.length > 0) { for (String address : copyTo) { if (!invalidAddressList.contains(address)) { validCopyToAdressesList.add(address); } } } String[] validToAdressesArray = new String[validToAdressesList.size()]; validToAdressesList.toArray(validToAdressesArray); helper.setTo(validToAdressesList.toArray(validToAdressesArray)); String[] validCopyToAdressesArray = new String[validCopyToAdressesList.size()]; validCopyToAdressesList.toArray(validCopyToAdressesArray); helper.setCc(validCopyToAdressesList.toArray(validCopyToAdressesArray)); for (String invalidAddress : invalidAddressList) { logger.error("Mail not sended to " + invalidAddress + "due its a invalid address"); } this.mailSender.send(message); } } } } }
From source file:com.autentia.wuija.mail.MailService.java
/** * send an e-mail/*from w w w . j av a 2 s .co m*/ * * @param to recipient e-mail * @param subject the subject of the e-mail * @param text the body of the e-mail * @param attachments an array of it * @throws EmailException if the e-mail cannot be prepare or send. */ public void send(String to, String subject, String text, File... attachments) { Assert.hasLength(to, "email 'to' needed"); Assert.hasLength(subject, "email 'subject' needed"); Assert.hasLength(text, "email 'text' needed"); if (log.isDebugEnabled()) { final boolean usingPassword = StringUtils.isNotBlank(mailSender.getPassword()); log.debug("Sending email to: '" + to + "' [through host: '" + mailSender.getHost() + ":" + mailSender.getPort() + "', username: '" + mailSender.getUsername() + "' usingPassword:" + usingPassword + "]."); log.debug("isActive: " + active); } if (!active) { return; } final MimeMessage message = mailSender.createMimeMessage(); try { // use the true flag to indicate you need a multipart message final MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setFrom(getFrom()); helper.setText(text); if (attachments != null) { for (int i = 0; i < attachments.length; i++) { // let's attach each file final FileSystemResource file = new FileSystemResource(attachments[i]); helper.addAttachment(attachments[i].getName(), file); if (log.isDebugEnabled()) { log.debug("File '" + file + "' attached."); } } } } catch (MessagingException e) { final String msg = "Cannot prepare email message : " + subject + ", to: " + to; log.error(msg, e); throw new MailPreparationException(msg, e); } this.mailSender.send(message); }