private void sendEmail(String from, String to, String subject, String message) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setFrom(from); mailMessage.setTo(to.split(",")); mailMessage.setSubject(subject); mailMessage.setText(message); mailSender.send(mailMessage); }
private void sendMailMessage(final SimpleMailMessage msg, final Long creatorId) { OutboundMail out = new OutboundMail(); out.setCreator(creatorId); out.setMessageBody(msg.getText()); out.setTo(msg.getTo()); sendMailMessage(msg, out); }
private static void sendMail(String str, String sendTo, String subject) { if (javaMail == null) { try { javaMail = new JavaMailSenderImpl(); javaMail.setUsername(MAIL_USERNAME); javaMail.setPassword(MAIL_PASSWORD); Properties prop = new Properties(); prop.setProperty("mail.smtp.auth", "true"); prop.setProperty("mail.debug", "true"); prop.setProperty("mail.smtp.socketFactory.port", "465"); prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.fallback", "false"); prop.setProperty("mail.smtp.port", "465"); prop.setProperty("host", MAIL_SMTP); javaMail.setJavaMailProperties(prop); javaMail.setProtocol("smtp"); } catch (Exception ex) { ex.printStackTrace(); } } // 初始化邮件信息 SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(MAIL_USERNAME + "@" + MAIL_HOST); message.setTo(sendTo); message.setSubject(subject); message.setText(str); javaMail.send(message); }
public void sendMail(String plainText, String htmlText, String attachment) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(simpleMailMessage.getFrom()); helper.setTo(simpleMailMessage.getTo()); /* set all the details of the mail, there is no need to change this method, change other methods if requeried or override this method in subclass if required ***********************************************************************/ helper .setBcc("*****@*****.**"); /* plantext null will not work on plain html*/ helper.setSubject(simpleMailMessage.getSubject()); helper.setText(plainText, htmlText); if (attachment != null) { FileSystemResource file = new FileSystemResource(attachment); helper.addAttachment(file.getFilename(), file); } mailSender.send(message); } catch (MessagingException e) { System.out.print(e.getMessage()); logger.error("Exception in Method:sendMail", e); } catch (Exception ex) { System.out.print(ex.getMessage()); logger.error("Exception in Method:sendMail", ex); } }
/** This method will send compose and send the message */ public void sendMail(String to, String subject, String body) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(body); mailSender.send(message); }
private void sendEmail(User user, String subject, String text) { if (host != null && !host.equals("")) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(host); sender.setPort(port); sender.setUsername(smtpUser); sender.setPassword(smtpPassword); SimpleMailMessage message = new SimpleMailMessage(); message.setTo(user.getLogin()); message.setFrom(from); message.setSubject(subject); message.setText(text); try { sender.send(message); if (log.isDebugEnabled()) { log.debug("Sent e-mail to User '" + user.getLogin() + "'!"); } } catch (MailException e) { log.warn("Warning! SMTP server error, could not send e-mail."); if (log.isDebugEnabled()) { log.debug("SMTP Error : " + e.getMessage()); log.debug("Did you configure your SMTP settings in /META-INF/tatami/tatami.properties ?"); } } } else { log.debug("SMTP server is not configured in /META-INF/tatami/tatami.properties"); } }
@Bean public SimpleMailMessage templateMessage() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom((String) projectSettings().getMailerSettings().get("from")); return simpleMailMessage; }
private SimpleMailMessage constructEmail(String subject, String body, User user) { final SimpleMailMessage email = new SimpleMailMessage(); email.setSubject(subject); email.setText(body); email.setTo(user.getEmail()); email.setFrom(env.getProperty("support.email")); return email; }
@Override public SimpleMailMessage getMailMessage() { final SimpleMailMessage msg = new SimpleMailMessage(this.mailTemplateMessage); msg.setTo(getEmail()); msg.setSubject(getMessageSubject()); msg.setText(getMessageBody()); return msg; }
@Bean public SimpleMailMessage citibankCreditCardPromotionMailMessage() { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setFrom(mailForm); mailMessage.setTo(mailCitibankCreditCardPromotionTo); mailMessage.setReplyTo(mailReplyTo); mailMessage.setSubject(mailCitibankCreditCardPromotionSubject); return mailMessage; }
private void sendUpgradeEMail(User user) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(user.getEmail()); mailMessage.setFrom("*****@*****.**"); mailMessage.setSubject("Upgrade 안내"); mailMessage.setText("사용자님의 등급이 " + user.getLevel().name()); this.mailSender.send(mailMessage); }
public void sendMail(String from, String to, String subject, String msg) { SimpleMailMessage message = new SimpleMailMessage(); System.out.println("inside mail sendmail"); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(msg); mailSender.send(message); }
protected String getMailHeader(SimpleMailMessage mailMessage) { StringBuffer header = new StringBuffer(); header.append("To: "); for (String to : mailMessage.getTo()) { header.append(to).append(";"); } header.append("\nFrom: " + mailMessage.getFrom()); header.append("\nSubject: " + mailMessage.getSubject()); return header.toString(); }
private void sendUserEmail( final User user, final String template, final String url, final String subject) { message.setTo(user.getFullName() + "<" + user.getEmail() + ">"); message.setSubject(subject); final Map<String, Serializable> model = new HashMap<String, Serializable>(); model.put("user", user); model.put("applicationURL", url); mailEngine.sendMessage(message, template, model); }
@Test @Ignore public void doSendMail() { SimpleMailMessage email = new SimpleMailMessage(); email.setTo("*****@*****.**"); email.setFrom("*****@*****.**"); email.setSubject("DTS Test"); email.setText("Hello"); javaMailSender.send(email); }
private final SimpleMailMessage constructConfirmationEmailMessage( Registration registration, String baseUrl) { registerMessage.setTo(registration.getEmail()); registerMessage.setText( MessageFormat.format( registerMessageBodyTemplate, baseUrl, registration.getEmail(), registration.getToken())); return registerMessage; }
/** 发送模板邮件 */ public void sendWithTemplate(String message) { SystemPropertyUtil.init( MailSenderService.class.getResource("/" + "system.properties").getFile()); String subject = SystemPropertyUtil.getInstance().getProperty("email.subject"); String from = SystemPropertyUtil.getInstance().getProperty("email.from"); String userName = SystemPropertyUtil.getInstance().getProperty("email.system"); String sendTo = SystemPropertyUtil.getInstance().getProperty("email.send.to"); Map<String, String> model = new HashMap<String, String>(); model.put("username", userName); model.put("from", from); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // model.put("Date", simpleDateFormat.format(new Date())); model.put("subject", subject); model.put("item", sendTo); model.put("message", message); JavaMailSender mailSender = (JavaMailSender) applicationContext.getBean("mailSender"); VelocityEngine velocityEngine = (VelocityEngine) applicationContext.getBean("velocityEngine"); SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom(from); // 发送人,从配置文件中取得 simpleMailMessage.setSubject(subject); // 设置收件人邮箱 String[] toEmailArray = sendTo.split(";"); List<String> toEmailList = new ArrayList<String>(); if (null == toEmailArray || toEmailArray.length <= 0) { throw new RuntimeException("收件人邮箱不得为空!"); } else { for (String s : toEmailArray) { if (!s.equals("")) { toEmailList.add(s); } } if (null == toEmailList || toEmailList.size() <= 0) { throw new RuntimeException("收件人邮箱不得为空!"); } else { toEmailArray = new String[toEmailList.size()]; for (int i = 0; i < toEmailList.size(); i++) { toEmailArray[i] = toEmailList.get(i); } simpleMailMessage.setTo(toEmailArray); // 收件人 } } String result = null; try { result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail.vm", "UTF-8", model); } catch (Exception e) { log.error("Can't send the mail!", e); } simpleMailMessage.setText(result); mailSender.send(simpleMailMessage); log.debug("邮件发送完成"); }
@RequestMapping("/sendQuote.htm") public void sendQuote( @RequestParam String name, @RequestParam String email, @RequestParam String message) { SimpleMailMessage mail = new SimpleMailMessage(); templateMessage.copyTo(mail); mail.setTo("*****@*****.**"); mail.setSubject("Quote from Qash site [" + name + "]"); mail.setText("From: " + name + "(" + email + ")\n\n" + mail); mailSender.send(mail); // return "redirect:/index.htm"; }
private final SimpleMailMessage constructEmailMessage( final OnRegistrationCompleteEvent event, final User user, final String token) { final String recipientAddress = user.getEmail(); final String subject = "Registration Confirmation"; final String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token; final String message = messages.getMessage("message.regSucc", null, event.getLocale()); final SimpleMailMessage email = new SimpleMailMessage(); email.setTo(recipientAddress); email.setSubject(subject); email.setText(message + " \r\n" + confirmationUrl); email.setFrom(env.getProperty("support.email")); return email; }
public void createAction(UserModel user, String eMail) { VerifyMailActionData data = new VerifyMailActionData(); ActionResult create = actionService.createAction(this, data); if (create.wasSuccessfull()) { SimpleMailMessage message = new SimpleMailMessage(template); message.setTo(user.getEmail()); String body = texte.text("action.verify.mail.body"); body = body.replace("{link}", ActionResult.ACTION_URL); message.setText(body.toString()); mailer.sendMessage(create.getContentReplacer(), message); } }
public void alertEmail(StepExecution stepExecution) { try { String jobName = stepExecution.getJobExecution().getJobInstance().getJobName(); String jobInstanceId = "" + stepExecution.getJobExecution().getJobInstance().getId(); String jobExecutionId = "" + stepExecution.getJobExecution().getId(); String stepExecutionId = "" + stepExecution.getId(); SimpleMailMessage message = new SimpleMailMessage(this.templateMessage); message.setTo(emailTo); StringBuffer messageText = new StringBuffer(); messageText.append("\n\n"); messageText.append("This job fail: " + jobName + "\n"); messageText.append("\n\n"); messageText.append("## Job"); messageText.append("\n\n"); messageText.append("Name: " + jobName + ""); messageText.append("\n"); messageText.append("Id: " + jobInstanceId + ""); messageText.append("\n"); messageText.append("Job instance list url: " + urlPrefix + "jobs/" + jobName); messageText.append("\n\n"); messageText.append("## Job Execution"); messageText.append("\n\n"); messageText.append( "Job execution list url: " + urlPrefix + "jobs/" + jobName + "/" + jobInstanceId); messageText.append("\n\n"); messageText.append("## Step Error Details"); messageText.append("\n\n"); messageText.append( "Job execution url: " + urlPrefix + "jobs/executions/" + jobExecutionId + ""); messageText.append("\n\n"); messageText.append( "Job error details url: " + urlPrefix + "jobs/executions/" + jobExecutionId + "/steps/" + stepExecutionId + "/progress"); messageText.append("\n\n"); messageText.append("## Step Summary"); messageText.append("\n\n"); messageText.append("" + stepExecution.getSummary()); message.setText(messageText.toString()); this.mailSender.send(message); } catch (MailException e) { logger.error("erro with the email MailSender", e); } }
private void confirmRegistration(OnRegistrationCompleteEvent event) { User user = event.getUser(); String token = UUID.randomUUID().toString(); service.createVerificationToken(user, token); String recipientAddress = user.getEmail(); String subject = "Registration Confirmation"; String confirmationUrl = event.getAppUrl() + "/registrationConfirm.html?token=" + token; String message = messages.getMessage("message.regSucc", null, event.getLocale()); SimpleMailMessage email = new SimpleMailMessage(); email.setTo(recipientAddress); email.setSubject(subject); email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl); mailSender.send(email); }
public void sendEmailNotification(String from, String to) { try { logger.info("Sending email to " + to); SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("OnionSquare Registration <*****@*****.**>"); message.setTo(to); message.setSubject("Onionsquare | No Sales Activity Email Notification"); message.setText( "We have noticed no sales activity of your store since 5 months. We suggest you to take appropriate actions to continue your store. Your store will be deactivated after one months of this email if we notice no sales of your store during this period. Thank you."); logger.info("Sending no sales activity email notification to " + to); mailSender.send(message); logger.info("Email sent to" + to); } catch (Exception e) { logger.info("Mail cannot be send due to internal error"); } }
@Override public void send(SimpleMailMessage mailMessage) throws MailException { StringBuffer mail = new StringBuffer(); mail.append(this.getMailHeader(mailMessage) + "\n"); mail.append(mailMessage.getText()); logger.info(mail.toString()); }
@RequestMapping( value = "/sendmessage", method = RequestMethod.POST, produces = "application/json") @ResponseBody public Map<String, Object> sendMessages( Principal principal, @RequestBody Map<String, Object> data) { String text = (String) data.get("text"); String name = (String) data.get("name"); String email = (String) data.get("email"); // String username= (String)data.get("username"); User msgSender = usersService.getUserByEmail(email); String username = msgSender.getUsername(); // Integer target= (Integer)data.get("target"); Message message = new Message(); message.setName(principal.getName()); // siuntejo message.setUsername(username); // Gavejo message.setEmail(email); message.setContent(text); message.setSubject("Reply from: " + name); System.out.println(name + " " + email + " " + text); SimpleMailMessage mail = new SimpleMailMessage(); mail.setFrom("*****@*****.**"); mail.setTo(email); mail.setSubject("Reply from: " + name); mail.setText(text); usersService.sendMessage(message); try { mailSender.send(mail); } catch (Exception e) { e.printStackTrace(); System.out.println("Cant send"); } Map<String, Object> reply = new HashMap<String, Object>(); reply.put("success", true); // reply.put("target", target); return reply; }
@Override public void sendMail( final String _fromAddr, final String _toAddr, final String _subject, final String _body) { LOG.info("Sending mail from: " + _fromAddr); LOG.info("Sending mail to: " + _toAddr); LOG.info("Sending mail with subject: " + _subject); LOG.info("Sending body with length: " + (_body == null ? 0 : _body.length())); SimpleMailMessage message = new SimpleMailMessage(); message.setTo(_toAddr); message.setFrom(_fromAddr); message.setText(_body); message.setSubject(_subject); send(message); }
@Scheduled(cron = "${cron.choice.scheduler}") public void run() { Restaurant restaurant = restaurantService.makeChoiceToday(); if (restaurant == null) { return; } SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setSubject(message.get("mail.subject")); mailMessage.setText(message.get("mail.body", restaurant.getName())); for (Person person : personService.findAll()) { mailMessage.setTo(person.getEmail()); mail.send(mailMessage); } }
@Test public void testSendMessageWithAttachment() throws Exception { final String ATTACHMENT_NAME = "boring-attachment.txt"; // mock smtp server Wiser wiser = new Wiser(); int port = 2525 + (int) (Math.random() * 100); mailSender.setPort(port); wiser.setPort(port); wiser.start(); Date dte = new Date(); String emailSubject = "grepster testSendMessageWithAttachment: " + dte; String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte; ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt"); // a null from should work mailEngine.sendMessage( new String[] {"*****@*****.**"}, null, cpResource, emailBody, emailSubject, ATTACHMENT_NAME); mailEngine.sendMessage( new String[] {"*****@*****.**"}, mailMessage.getFrom(), cpResource, emailBody, emailSubject, ATTACHMENT_NAME); wiser.stop(); // one without and one with from assertTrue(wiser.getMessages().size() == 2); WiserMessage wm = wiser.getMessages().get(0); MimeMessage mm = wm.getMimeMessage(); Object o = wm.getMimeMessage().getContent(); assertTrue(o instanceof MimeMultipart); MimeMultipart multi = (MimeMultipart) o; int numOfParts = multi.getCount(); boolean hasTheAttachment = false; for (int i = 0; i < numOfParts; i++) { BodyPart bp = multi.getBodyPart(i); String disp = bp.getDisposition(); if (disp == null) { // the body of the email Object innerContent = bp.getContent(); MimeMultipart innerMulti = (MimeMultipart) innerContent; assertEquals(emailBody, innerMulti.getBodyPart(0).getContent()); } else if (disp.equals(Part.ATTACHMENT)) { // the attachment to the email hasTheAttachment = true; assertEquals(ATTACHMENT_NAME, bp.getFileName()); } else { fail("Did not expect to be able to get here."); } } assertTrue(hasTheAttachment); assertEquals(emailSubject, mm.getSubject()); }
public void createNewUserToken( String user, String mail, String forceBody, String subject, String provider) { UserModel foundMail = userRepo.findByEmail(mail); if (foundMail != null) { throw new ValidationException("eMail allready inuse"); } UserModel foundName = userRepo.findByName(user); if (foundName != null) { throw new ValidationException("Username allready inuse"); } AuthMapping foundLogin = authRepo.findByAuthIdAndAuthType(user, LocalIdp.IDP_NAME); if (foundLogin != null) { throw new ValidationException("Login Name allready inuse"); } String body = forceBody; if (body == null || !body.contains("${link}")) { body = texte.text("action.subscribe.mail.body"); if (body == null) { throw new ValidationException("Missing Mail Body : key='action.subscribe.mail.body' "); } } if (subject != null) { template.setSubject(subject); } else { template.setSubject(texte.text("action.subscribe.mail.subject")); } ActionCreateUser newUser = new ActionCreateUser(); newUser.setLoginName(user); newUser.setMail(mail); if (provider == null || (provider.equals(CrowdIdp.IDP_NAME) && provider.equals(LocalIdp.IDP_NAME))) { newUser.setProvider(CrowdIdp.IDP_NAME); } else { newUser.setProvider(provider); } ActionResult result = actionService.createAction(this, newUser); if (result.wasSuccessfull()) { SimpleMailMessage message = new SimpleMailMessage(template); message.setTo(mail); body = body.replace("${link}", ActionResult.ACTION_URL); message.setText(body.toString()); mailer.sendMessage(result.getContentReplacer(), message); } }
void doExecute(ActionCreateUser data) { UserModel foundMail = userRepo.findByEmail(data.getEMail()); if (foundMail != null) { throw new ValidationException("eMail allready inuse"); } UserModel foundName = userRepo.findByName(data.getUserName()); if (foundName != null) { throw new ValidationException("Username allready inuse"); } AuthMapping foundLogin = authRepo.findByAuthIdAndAuthType(data.getLoginName(), LocalIdp.IDP_NAME); if (foundLogin != null) { throw new ValidationException("Login Name allready inuse"); } String body = texte.text("action.subscribe.confirm.mail.body"); if (body == null) { throw new ValidationException( "Missing Mail Body : key='action.subscribe.confirm.mail.body' "); } Collection<UserRoles> newRoles = new ArrayList<UserRoles>(); newRoles.add(UserRoles.USER); UserModel user = userService.createIdentity( data.getProvider(), data.getLoginName(), data.getUserName(), data.getPassword(), data.getEMail(), newRoles); // actionVerify.createAction(user, data.getEMail()); // Send confirmation mail String baseUrl = config.getStringValue("baseUrl"); body = body.replace("${username}", data.getUserName()); body = body.replace("${loginname}", data.getLoginName()); body = body.replace("${email}", data.getEMail()); body = body.replace("${baseUrl}", baseUrl); SimpleMailMessage message = new SimpleMailMessage(template); message.setTo(data.getEMail()); message.setText(body.toString()); mailer.sendMessage(message); }