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); }
@Override public ServiceResult send(String toMailAddr, String subject, String content, Integer mailType) { ServiceResult result = new ServiceResult(false); MimeMessage mailMessage = mailSender.createMimeMessage(); // 设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper messageHelper = null; // 设置邮件参数 SystemConfig systemConfig = systemConfigDAO.load(1); try { messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8"); messageHelper.setFrom( systemConfig.getEmailCode(), systemConfig.getCompanyName()); // 发送者,这里还可以另起Email别名,不用和xml里的username一致 messageHelper.setTo(toMailAddr); // 接受者 messageHelper.setSubject(subject); // 主题 messageHelper.setText(content, true); // 邮件内容 mailSender.send(mailMessage); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } MailsHistory mailsHistory = new MailsHistory(); mailsHistory.setTitle(subject); mailsHistory.setContent(content); mailsHistory.setReceiveIDs(toMailAddr); mailsHistory.setMailType(mailType); mailsHistoryDAO.save(mailsHistory); result.setIsSuccess(true); return result; }
public void sendEmail(String email, String template, String subject, Map<String, Object> vars) throws RegistrationException { try { final Context ctx = new Context(); if (vars != null) { for (String var : vars.keySet()) { ctx.setVariable(var, vars.get(var)); } } final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); message.setSubject(subject); message.setFrom(mailUser); message.setTo(email); // Create the HTML body using Thymeleaf final String htmlContent = this.templateEngine.process(template, ctx); message.setText(htmlContent, true); // Send mail mailSender.send(mimeMessage); } catch (Exception e) { e.printStackTrace(); throw new RegistrationException(e); } }
private void sendEmail(String to, String subject, String body, Boolean htmlEmail) throws Exception { try { JavaMailSenderImpl mailSender = (JavaMailSenderImpl) appContext.getBean("mailSender"); Properties javaMailProperties = mailSender.getJavaMailProperties(); if (null != javaMailProperties) { if (javaMailProperties.get("mail.smtp.localhost") == null || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) { javaMailProperties.put("mail.smtp.localhost", "localhost"); } } MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail); helper.setFrom(EmailEngine.getAdminEmail()); helper.setTo(processMultipleImailAddresses(to.trim())); helper.setSubject(subject); helper.setText(body, true); mailSender.send(mimeMessage); logger.debug("Email sent successfully on {}", new Date()); } catch (MailException me) { logger.error("Email could not be sent on {} due to: {}", new Date(), me.getMessage()); } }
@Before public void onSetUp() { smtpPort = smtpPort + (int) (Math.random() * 100); LocalizedTextUtil.addDefaultResourceBundle(Constants.BUNDLE_KEY); // Initialize ActionContext ConfigurationManager configurationManager = new ConfigurationManager(); configurationManager.addContainerProvider(new XWorkConfigurationProvider()); Configuration config = configurationManager.getConfiguration(); Container container = config.getContainer(); ValueStack stack = container.getInstance(ValueStackFactory.class).createValueStack(); stack.getContext().put(ActionContext.CONTAINER, container); ActionContext.setContext(new ActionContext(stack.getContext())); ActionContext.getContext().setSession(new HashMap<String, Object>()); // change the port on the mailSender so it doesn't conflict with an // existing SMTP server on localhost JavaMailSenderImpl mailSender = (JavaMailSenderImpl) applicationContext.getBean("mailSender"); mailSender.setPort(getSmtpPort()); mailSender.setHost("localhost"); // populate the request so getRequest().getSession() doesn't fail in BaseAction.java ServletActionContext.setRequest(new MockHttpServletRequest()); }
@Async public void sendEmail( String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug( "Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage()); } }
private void SpringSendTextMail(SendMailContent content) { this.organMailContent(); final String toMail = content.getToMail(); final String fromMail = content.getFromMail(); final String subject = content.getSubject(); final String text = content.getSendText(); try { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); final MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "GBK"); messageHelper.setTo(toMail); messageHelper.setFrom(fromMail); messageHelper.setSubject(subject); messageHelper.setText( "<html><head>" + setCss() + "</head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=\"GBK\" /> <body>" + text + "</body></html>", true); mailSender.send(mailMessage); } catch (Exception ex) { ex.printStackTrace(); } }
@Bean public JavaMailSender mailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setDefaultEncoding("UTF-8"); mailSender.setHost(mailHost); mailSender.setPort(new Integer(mailPort)); return mailSender; }
@Before public void onSetUp() { smtpPort = smtpPort + (int) (Math.random() * 100); // change the port on the mailSender so it doesn't conflict with an // existing SMTP server on localhost final JavaMailSenderImpl mailSender = (JavaMailSenderImpl) applicationContext.getBean("mailSender"); mailSender.setPort(smtpPort); mailSender.setHost("localhost"); }
@Bean public MailSender mailSender() { JavaMailSenderImpl ms = new JavaMailSenderImpl(); ms.setJavaMailProperties((Properties) projectSettings().getMailerSettings().get("properties")); ms.setUsername((String) projectSettings().getMailerSettings().get("username")); ms.setPassword((String) projectSettings().getMailerSettings().get("password")); return ms; }
@Bean(name = "mailSender") public JavaMailSenderImpl mailSender() { JavaMailSenderImpl sender = new JavaMailSenderImpl(); if (this.session != null) { sender.setSession(this.session); } else { applyProperties(sender); } return sender; }
@Bean public JavaMailSender mailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("localhost"); mailSender.setPort(25); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.transport.protocol", "smtp"); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; }
public static void init() { mailSenderImpl.setHost(PropertyUtils.getProperty("imti.mail.host")); mailSenderImpl.setUsername(PropertyUtils.getProperty("imti.mail.username")); mailSenderImpl.setPassword(PropertyUtils.getProperty("imti.mail.password")); Properties prop = new Properties(); prop.setProperty("mail.smtp.auth", PropertyUtils.getProperty("imti.mail.smtp.auth")); prop.setProperty("mail.smtp.timeout", PropertyUtils.getProperty("imti.mail.smtp.timeout")); mailSenderImpl.setJavaMailProperties(prop); }
private JavaMailSender getRandomBusinessMailSender() { Random random = new Random(); int r = random.nextInt(Constants.MAIL_BUSINESS_SETTINGS.length - 1); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(Constants.MAIL_BUSINESS_SETTINGS[r][0]); mailSender.setUsername(Constants.MAIL_BUSINESS_SETTINGS[r][2]); mailSender.setPassword(Constants.MAIL_BUSINESS_SETTINGS[r][3]); Properties smtpAuthProperties = new Properties(); smtpAuthProperties.setProperty("mail.smtp.auth", "true"); mailSender.setJavaMailProperties(smtpAuthProperties); return mailSender; }
JavaMailSender createSender() { Map<String, String> settings = systemSettingsStore.getSettings(); String host = settings.get(SystemSettingsStore.MAIL_HOST_NAME); int port = Integer.parseInt(settings.get(SystemSettingsStore.MAIL_HOST_PORT)); if (StringUtils.isNotBlank(host)) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(host); sender.setPort(port); return sender; } else { return null; } }
@Override public Result check() { try { javaMailSender .getSession() .getTransport() .connect( javaMailSender.getHost(), javaMailSender.getUsername(), javaMailSender.getPassword()); return Result.healthy(); } catch (Exception e) { log.debug("Cannot connect to e-mail server: {}", e); return Result.unhealthy("Cannot connect to e-mail server"); } }
public void postMail( String[] recipients, String subject, String message, String from, String[] cc) throws MessagingException { sender.setUsername((String) properties.getProperty("mail.user")); sender.setPassword((String) properties.getProperty("mail.password")); sender.setHost((String) properties.getProperty("mail.smtp.host")); String portString = (String) properties.getProperty("mail.smtp.port"); sender.setPort(Integer.valueOf(portString)); sender.setProtocol((String) properties.getProperty("mail.transport.protocol")); sender.setJavaMailProperties(properties); MimeMessage mimeMessage = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "UTF-8"); helper.setFrom(from); helper.setText(message); helper.setSubject(subject); if (cc != null) { helper.setCc(cc); } for (String receiver : recipients) { if (receiver != null) { helper.setTo(receiver); sender.send(mimeMessage); } } }
/** * Convenience method for sending messages with attachments. * * @param recipients array of e-mail addresses * @param sender e-mail address of sender * @param resource attachment from classpath * @param bodyText text in e-mail * @param subject subject of e-mail * @param attachmentName name for attachment * @throws MessagingException thrown when can't communicate with SMTP server */ public void sendMessage( String[] recipients, String sender, ClassPathResource resource, String bodyText, String subject, String attachmentName) throws MessagingException { MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage(); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipients); // use the default sending if no sender specified if (sender == null) { helper.setFrom(defaultFrom); } else { helper.setFrom(sender); } helper.setText(bodyText); helper.setSubject(subject); helper.addAttachment(attachmentName, resource); ((JavaMailSenderImpl) mailSender).send(message); }
@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()); }
/** @param args */ public static void main(String[] args) throws Exception { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHost("smtp.163.com"); // 建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); // 设置收件人,寄件人 messageHelper.setTo("*@qq.com"); messageHelper.setFrom("*@163.com"); messageHelper.setSubject("spring测试HTML邮件!"); // true 表示启动HTML格式的邮件 messageHelper.setText( "<html><head></head><body><h1>hello!!spring html Mail</h1></body></html>", true); senderImpl.setUsername("*"); // 根据自己的情况,设置username senderImpl.setPassword("*"); // 根据自己的情况, 设置password Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确 prop.put("mail.smtp.timeout", "25000"); senderImpl.setJavaMailProperties(prop); // 发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功.."); }
@Bean public JavaMailSenderImpl javaMailSender(JHipsterProperties jHipsterProperties) { log.debug("Configuring mail server"); String host = jHipsterProperties.getMail().getHost(); int port = jHipsterProperties.getMail().getPort(); String user = jHipsterProperties.getMail().getUsername(); String password = jHipsterProperties.getMail().getPassword(); String protocol = jHipsterProperties.getMail().getProtocol(); Boolean tls = jHipsterProperties.getMail().isTls(); Boolean auth = jHipsterProperties.getMail().isAuth(); JavaMailSenderImpl sender = new JavaMailSenderImpl(); if (host != null && !host.isEmpty()) { sender.setHost(host); } else { log.warn("Warning! Your SMTP server is not configured. We will try to use one on localhost."); log.debug("Did you configure your SMTP settings in your application.yml?"); sender.setHost(DEFAULT_HOST); } sender.setPort(port); sender.setUsername(user); sender.setPassword(password); Properties sendProperties = new Properties(); sendProperties.setProperty(PROP_SMTP_AUTH, auth.toString()); sendProperties.setProperty(PROP_STARTTLS, tls.toString()); sendProperties.setProperty(PROP_TRANSPORT_PROTO, protocol); sender.setJavaMailProperties(sendProperties); return sender; }
@Bean public JavaMailSenderImpl javaMailSender() { log.debug("Configuring mail server"); String host = propertyResolver.getProperty(PROP_HOST, DEFAULT_PROP_HOST); int port = propertyResolver.getProperty(PROP_PORT, Integer.class, 0); String user = propertyResolver.getProperty(PROP_USER); String password = propertyResolver.getProperty(PROP_PASSWORD); String protocol = propertyResolver.getProperty(PROP_PROTO); Boolean tls = propertyResolver.getProperty(PROP_TLS, Boolean.class, false); Boolean auth = propertyResolver.getProperty(PROP_AUTH, Boolean.class, false); JavaMailSenderImpl sender = new JavaMailSenderImpl(); if (host != null && !host.isEmpty()) { sender.setHost(host); } else { log.warn("Warning! Your SMTP server is not configured. We will try to use one on localhost."); log.debug("Did you configure your SMTP settings in your application.yml?"); sender.setHost(DEFAULT_HOST); } sender.setPort(port); sender.setUsername(user); sender.setPassword(password); Properties sendProperties = new Properties(); sendProperties.setProperty(PROP_SMTP_AUTH, auth.toString()); sendProperties.setProperty(PROP_STARTTLS, tls.toString()); sendProperties.setProperty(PROP_TRANSPORT_PROTO, protocol); sender.setJavaMailProperties(sendProperties); return sender; }
public void updateJavaMailSender() { javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(host); if (smtpAuth) { javaMailSender.setUsername(username); javaMailSender.setPassword(password); } javaMailSender.setDefaultEncoding("UTF-8"); javaMailSender.setJavaMailProperties(this.getProperties()); logger.info("host : {}", host); logger.info("username : {}", username); logger.info("password : {}", password); logger.info("getProperties : {}", getProperties()); }
@Override public Result check() { try { javaMailSender.getSession().getTransport().connect(); return Result.healthy(); } catch (MessagingException e) { log.debug("Cannot connect to e-mail server: {}", e); return Result.unhealthy("Cannot connect to e-mail server"); } }
@Override public void sendMessage(String recipient, String subject, String body) { MimeMessagePreparator message = prepareMessage(recipient, subject, body); try { javaMailSender.send(message); LOG.trace("Message sent to: " + recipient); } catch (MailException e) { LOG.error("Error during sending mail message.", e); } }
private void sendEmail(Task.Status exitStatus, File logFile) throws IOException, MessagingException, TemplateException { String smtpServer = RepoxContextUtil.getRepoxManager().getConfiguration().getSmtpServer(); if (smtpServer == null || smtpServer.isEmpty()) { return; } String fromEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getDefaultEmail(); String recipientsEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getAdministratorEmail(); String adminMailPass = RepoxContextUtil.getRepoxManager().getConfiguration().getMailPassword(); String subject = "REPOX Data Source ingesting finished. Exit status: " + exitStatus.toString(); EmailSender emailSender = new EmailSender(); String pathIngestFile = URLDecoder.decode( Thread.currentThread().getContextClassLoader().getResource("ingest.html.ftl").getFile(), "ISO-8859-1"); emailSender.setTemplate( pathIngestFile.substring(0, pathIngestFile.lastIndexOf("/")) + "/ingest"); HashMap map = new HashMap<String, String>(); map.put("exitStatus", exitStatus.toString()); map.put("id", id); JavaMailSenderImpl mail = new JavaMailSenderImpl(); // mail.setUsername(fromEmail); mail.setUsername(recipientsEmail); mail.setPassword(adminMailPass); mail.setPort(25); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); mail.setJavaMailProperties(props); emailSender.setMailSender(mail); emailSender.sendEmail(recipientsEmail, fromEmail, subject, map, logFile.getAbsolutePath()); }
public boolean send(String subject, String to, String content) { MimeMessage msg = mailSend.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(msg, false, "UTF-8"); helper.setFrom(new InternetAddress(from, personal)); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSend.send(msg); return true; } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); // return false; } return false; }
@Override protected void doHealthCheck(Health.Builder builder) throws Exception { log.debug("Initializing JavaMail health indicator"); try { javaMailSender .getSession() .getTransport() .connect( javaMailSender.getHost(), javaMailSender.getPort(), javaMailSender.getUsername(), javaMailSender.getPassword()); builder.up(); } catch (MessagingException e) { log.debug("Cannot connect to e-mail server. Error: {}", e.getMessage()); builder.down(e); } }
@Bean public JavaMailSender mailSender() { JavaMailSender mailSender = null; if (isMailSendingConfigured()) { mailSender = new JavaMailSenderImpl(); ((JavaMailSenderImpl) mailSender).setHost(host); ((JavaMailSenderImpl) mailSender).setPort(port); if (!StringUtils.isEmpty(userName)) { ((JavaMailSenderImpl) mailSender).setUsername(userName); } if (!StringUtils.isEmpty(password)) { ((JavaMailSenderImpl) mailSender).setPassword(password); } ((JavaMailSenderImpl) mailSender).setJavaMailProperties(getJavaMailProperties()); } else { mailSender = new DummyEmailSender(); } return mailSender; }
public static void main(String[] args) throws Exception { String smtpServer = RepoxContextUtil.getRepoxManager().getConfiguration().getSmtpServer(); if (smtpServer == null || smtpServer.isEmpty()) { return; } String fromEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getDefaultEmail(); String recipientsEmail = RepoxContextUtil.getRepoxManager().getConfiguration().getAdministratorEmail(); String adminMailPass = RepoxContextUtil.getRepoxManager().getConfiguration().getMailPassword(); String subject = "REPOX Data Source ingesting finished. Exit status: "; EmailSender emailSender = new EmailSender(); String pathIngestFile = URLDecoder.decode( Thread.currentThread().getContextClassLoader().getResource("ingest.html.ftl").getFile(), "ISO-8859-1"); emailSender.setTemplate( pathIngestFile.substring(0, pathIngestFile.lastIndexOf("/")) + "/ingest"); HashMap map = new HashMap<String, String>(); map.put("exitStatus", "OK"); map.put("id", "1111"); JavaMailSenderImpl mail = new JavaMailSenderImpl(); mail.setUsername(recipientsEmail); mail.setPassword(adminMailPass); mail.setPort(25); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "false"); mail.setJavaMailProperties(props); emailSender.setMailSender(mail); emailSender.sendEmail( recipientsEmail, fromEmail, subject, map, "C:\\Users\\GPedrosa\\Desktop\\indexSec.txt"); }