org.springframework.mail.javamail.JavaMailSenderImpl Java Examples

The following examples show how to use org.springframework.mail.javamail.JavaMailSenderImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailUtil.java    From boubei-tss with Apache License 2.0 8 votes vote down vote up
public static void send(String subject, String text, String receiver[], String _ms) {
	if(receiver == null || receiver.length == 0) {
		log.error("收件人不能为空"); 
		return;
	}
	
	JavaMailSenderImpl sender = MailUtil.getMailSender(_ms);
	try {
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setFrom( getEmailFrom(_ms) ); // 发送者,这里还可以另起Email别名
		mail.setTo( preCheatEmails(receiver) );
		mail.setSubject(subject);    // 主题
		mail.setText(text);         // 邮件内容
		
		sender.send(mail);
	} 
	catch (Exception e) {
		log.error("发送文本邮件(" +subject+ ")出错了, " + receiver + ":" + e.getMessage());
	}
}
 
Example #2
Source File: AbstractMailService.java    From halo with GNU General Public License v3.0 8 votes vote down vote up
/**
 * Test connection with email server.
 */
@Override
public void testConnection() {
    JavaMailSender javaMailSender = getMailSender();
    if (javaMailSender instanceof JavaMailSenderImpl) {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) javaMailSender;
        try {
            mailSender.testConnection();
        } catch (MessagingException e) {
            throw new EmailException("无法连接到邮箱服务器,请检查邮箱配置.[" + e.getMessage() + "]", e);
        }
    }
}
 
Example #3
Source File: EmailNotificationService.java    From jsflight with Apache License 2.0 7 votes vote down vote up
@PostConstruct
public void init()
{
    Settings settings = settingsService.getSettings();
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    if (!settings.getSmtpServer().isEmpty())
    {
        javaMailSender.setHost(settings.getSmtpServer());
    }
    if (!settings.getSmtpPort().isEmpty())
    {
        javaMailSender.setPort(Integer.parseInt(settings.getSmtpPort()));
    }

    javaMailSender.setUsername(settings.getStmpUser());
    javaMailSender.setPassword(settings.getStmpPassword());

    javaMailSender.setJavaMailProperties(getMailProperties(settings));

    sender = javaMailSender;
}
 
Example #4
Source File: JavaMailSenderFactoryTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testCreateMailSenderWithSpecifiedProperties() {
  final Properties javaMailProps = new Properties();
  javaMailProps.put("mail.debug", "true"); // specify
  javaMailProps.put("mail.smtp.starttls.enable", "false"); // override
  when(mailSettings.getJavaMailProperties()).thenReturn(javaMailProps);

  JavaMailSenderImpl actual = javaMailSenderFactory.createMailSender(mailSettings);

  assertEquals("host", actual.getHost());
  assertEquals(1234, actual.getPort());
  assertEquals("username", actual.getUsername());
  assertEquals("password", actual.getPassword());
  assertEquals("UTF-8", actual.getDefaultEncoding());
  final Properties actualProperties = actual.getJavaMailProperties();
  assertEquals("false", actualProperties.getProperty("mail.smtp.starttls.enable"));
  assertEquals("false", actualProperties.getProperty("mail.smtp.quitwait"));
  assertEquals("true", actualProperties.getProperty("mail.smtp.auth"));
  assertEquals("true", actualProperties.getProperty("mail.debug"));
}
 
Example #5
Source File: JavaMailSenderFactory.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public JavaMailSenderImpl createMailSender(MailSettings mailSettings) {
  LOG.trace("createMailSender");
  JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  mailSender.setHost(mailSettings.getHost());
  mailSender.setPort(mailSettings.getPort());
  mailSender.setProtocol(mailSettings.getProtocol());
  mailSender.setUsername(mailSettings.getUsername());
  mailSender.setPassword(mailSettings.getPassword());
  mailSender.setDefaultEncoding(mailSettings.getDefaultEncoding().name());
  Properties properties = new Properties(defaultProperties);
  defaultProperties.setProperty(MAIL_SMTP_STARTTLS_ENABLE, mailSettings.isStartTlsEnabled());
  defaultProperties.setProperty(MAIL_SMTP_QUITWAIT, mailSettings.isQuitWait());
  defaultProperties.setProperty(MAIL_SMTP_AUTH, mailSettings.isAuthenticationRequired());
  defaultProperties.setProperty(MAIL_SMTP_FROM_ADDRESS, mailSettings.getFromAddress());
  properties.putAll(mailSettings.getJavaMailProperties());
  LOG.debug("Mail properties: {}; defaults: {}", properties, defaultProperties);
  mailSender.setJavaMailProperties(properties);
  return mailSender;
}
 
Example #6
Source File: MailMessageNotifier.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
public MailMessageNotifier(MailNotifyProperties config) {
    super(config);
    this.mailSender = new JavaMailSenderImpl();
    if (!isNull(config.getProperties())) {
        this.mailSender.setJavaMailProperties(new Properties() {
            private static final long serialVersionUID = 1395782904610029089L;

            {
                putAll(config.getProperties());
            }
        });
    }
    this.mailSender.setDefaultEncoding(config.getDefaultEncoding().name());
    this.mailSender.setProtocol(config.getProtocol());
    this.mailSender.setHost(config.getHost());
    this.mailSender.setPort(config.getPort());
    this.mailSender.setUsername(config.getUsername());
    this.mailSender.setPassword(config.getPassword());
}
 
Example #7
Source File: MailServerInfo.java    From lemon with Apache License 2.0 6 votes vote down vote up
public void updateJavaMailSender() {
    javaMailSender = new JavaMailSenderImpl();

    javaMailSender.setHost(host);
    javaMailSender.setPort(port);

    if (smtpAuth) {
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
    }

    javaMailSender.setDefaultEncoding("UTF-8");

    javaMailSender.setJavaMailProperties(this.getProperties());
    logger.debug("host : {}", host);
    logger.debug("port : {}", port);
    logger.debug("username : {}", username);
    logger.debug("password : {}", password);
    logger.debug("getProperties : {}", getProperties());
}
 
Example #8
Source File: EmailServiceImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the mail sender.
 *
 * @return the mail sender
 */
private JavaMailSender getMailSender() {
	final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

	final ApplicationConfiguration smtpHostConfig = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_HOST, SMTP_HOST, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_HOST, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_HOST, "localhost");
	final ApplicationConfiguration smtpPort = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_PORT, SMTP_PORT, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_PORT, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_PORT, DEFAULT_SMTP_PORT);
	final ApplicationConfiguration smtpUsername = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_USERNAME, SMTP_USERNAME, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_USERNAME, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_USERNAME, "username");
	final ApplicationConfiguration smtpPassword = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_SECRET, SMTP_SECRET, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_SECRET, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_SECRET, "password");
	final ApplicationConfiguration smtpAuth = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_AUTH, SMTP_AUTH, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_AUTH, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_AUTH, "true");
	final ApplicationConfiguration smtpStartTlsEnable = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE, SMTP_STARTTLS_ENABLE, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_STARTTLS_ENABLE, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE, "true");


	javaMailSender.setHost(smtpHostConfig.getPropertyValue());
	javaMailSender.setPort(getSmtpPort(smtpPort));
	javaMailSender.setUsername(smtpUsername.getPropertyValue());
	javaMailSender.setPassword(smtpPassword.getPropertyValue());

	final Properties javaMailProperties = new Properties();

	javaMailProperties.setProperty(MAIL_SMTP_AUTH, smtpAuth.getPropertyValue());
	javaMailProperties.setProperty(MAIL_SMTP_STARTTLS_ENABLE, smtpStartTlsEnable.getPropertyValue());

	javaMailSender.setJavaMailProperties(javaMailProperties);

	return javaMailSender;
}
 
Example #9
Source File: MailAlarmService.java    From yugong with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void start() {
    super.start();
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setUsername(emailUsername);
    mailSender.setPassword(emailPassword);
    mailSender.setHost(emailHost);
    mailSender.setDefaultEncoding("UTF-8");
    Properties pros = new Properties();
    pros.put("mail.smtp.auth", true);
    pros.put("mail.smtp.timeout", 25000);
    pros.put("mail.smtp.port", stmpPort);
    pros.put("mail.smtp.socketFactory.port", stmpPort);
    pros.put("mail.smtp.socketFactory.fallback", false);
    if (sslSupport) {
        pros.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }

    mailSender.setJavaMailProperties(pros);

    this.mailSender = mailSender;
}
 
Example #10
Source File: SpringSmtpMailSender.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public SpringSmtpMailSender(BatchConfiguration batchConfiguration, UserGroupService userGroupService, JavaMailSenderImpl springMailSender) {
    Objects.requireNonNull(batchConfiguration, "batchConfiguration");
    Objects.requireNonNull(userGroupService, "userGroupService");
    Objects.requireNonNull(springMailSender, "mailSender");

    this.pinpointUrl = batchConfiguration.getPinpointUrl();
    this.batchEnv = batchConfiguration.getBatchEnv();
    this.userGroupService = userGroupService;
    this.springMailSender = springMailSender;

    try {
        senderEmailAddress = new InternetAddress(batchConfiguration.getSenderEmailAddress());
    } catch (AddressException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: EmailExchanger.java    From open-cloud with MIT License 6 votes vote down vote up
private JavaMailSenderImpl buildMailSender(EmailConfig config) {
    if (config == null) {
        throw new RuntimeException("缺少默认邮件服务器配置");
    }
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(config.getSmtpHost());
    sender.setUsername(config.getSmtpUsername());
    sender.setPassword(config.getSmtpPassword());
    sender.setDefaultEncoding("UTF-8");
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.starttls.enable", "true");
    props.setProperty("mail.smtp.starttls.required", "true");
    sender.setJavaMailProperties(props);
    return sender;
}
 
Example #12
Source File: SendEmailService.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String sendEmailTest(String emailFrom, String adminEmail, String emailServerHost, String emailServerPort, String emailServerUsername, String emailServerPassword) {
	log.debug("called sendEmailTest");
	try {
		String from = emailFrom;
		String to = adminEmail;
		String subject = "test subject";
		String body = "test body";
		JavaMailSenderImpl javaMailSender = constructJavaMailSender(emailServerHost, Integer.parseInt(emailServerPort), emailServerUsername, emailServerPassword);
		applyFixes(javaMailSender);
		sendEmail(javaMailSender, from, to, subject, body);
		return "all ok";
	} catch (Exception ex) {
		log.error("Error sending test email", ex);
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		return sw.toString(); // stack trace as a string
	}
}
 
Example #13
Source File: SmtpMailer.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private static JavaMailSender toMailSender(Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> conf) {
    JavaMailSenderImpl r = new CustomJavaMailSenderImpl();
    r.setDefaultEncoding("UTF-8");

    r.setHost(conf.get(SMTP_HOST).getRequiredValue());
    r.setPort(Integer.parseInt(conf.get(SMTP_PORT).getRequiredValue()));
    r.setProtocol(conf.get(SMTP_PROTOCOL).getRequiredValue());
    r.setUsername(conf.get(SMTP_USERNAME).getValueOrDefault(null));
    r.setPassword(conf.get(SMTP_PASSWORD).getValueOrDefault(null));

    String properties = conf.get(SMTP_PROPERTIES).getValueOrDefault(null);

    if (properties != null) {
        try {
            Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ByteArrayResource(
                    properties.getBytes(StandardCharsets.UTF_8)), "UTF-8"));
            r.setJavaMailProperties(prop);
        } catch (IOException e) {
            log.warn("error while setting the mail sender properties", e);
        }
    }
    return r;
}
 
Example #14
Source File: DefaultEmailNotifier.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
public DefaultEmailNotifier(NotifierProperties properties, TemplateManager templateManager) {
    super(templateManager);
    notifierId = properties.getId();

    DefaultEmailProperties emailProperties = new JSONObject(properties.getConfiguration())
        .toJavaObject(DefaultEmailProperties.class);
    ValidatorUtils.tryValidate(emailProperties);

    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(emailProperties.getHost());
    mailSender.setPort(emailProperties.getPort());
    mailSender.setUsername(emailProperties.getUsername());
    mailSender.setPassword(emailProperties.getPassword());
    mailSender.setJavaMailProperties(emailProperties.createJavaMailProperties());
    this.sender = emailProperties.getSender();
    this.javaMailSender = mailSender;
}
 
Example #15
Source File: SendEmailService.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String sendEmailTest(String emailFrom, String adminEmail, String emailServerHost, String emailServerPort, String emailServerUsername, String emailServerPassword) {
	log.debug("called sendEmailTest");
	try {
		String from = emailFrom;
		String to = adminEmail;
		String subject = "test subject";
		String body = "test body";
		JavaMailSenderImpl javaMailSender = constructJavaMailSender(emailServerHost, Integer.parseInt(emailServerPort), emailServerUsername, emailServerPassword);
		applyFixes(javaMailSender);
		sendEmail(javaMailSender, from, to, subject, body);
		return "all ok";
	} catch (Exception ex) {
		log.error("Error sending test email", ex);
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		return sw.toString(); // stack trace as a string
	}
}
 
Example #16
Source File: SendMail.java    From shark with Apache License 2.0 6 votes vote down vote up
public SendMail() {
	mailBean = new MailBean();
	mailSender = new JavaMailSenderImpl();
	mailSender.setPort(mailBean.getPORT());
	mailSender.setHost(mailBean.getHOST());
	mailSender.setUsername(mailBean.getUSERNAME());
	mailSender.setPassword(mailBean.getPASSWORD());
	Properties properties = new Properties();
	properties.setProperty("mail.smtp.auth", "true");
	mailSender.setJavaMailProperties(properties);
	mailMessage = new SimpleMailMessage();
	mailMessage.setFrom(mailBean.getFROM());
	mailMessage.setTo(mailBean.getTO());
	mailMessage.setSubject(mailBean.getSUBJECT());
	GetUserInfo getUserInfo = new GetUserInfo();
	mailMessage.setText("[version]:" + LoadVersion.getVersion() + "\n[javaVersion]:" + getUserInfo.getJavaVersion()
			+ "\n[osName]:" + getUserInfo.getOsName() + "\n[jvmName]:" + getUserInfo.getJvmName() + "\n[address]:"
			+ getUserInfo.getAddress() + "\n[hostName]:" + getUserInfo.getHostname() + "\n[startTime]:"
			+ getUserInfo.getStartTime());
}
 
Example #17
Source File: EmailConfiguration.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Bean
public JavaMailSender javaMailSender() {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    
    boolean isEmailEnabled = env.getProperty("email.enabled", Boolean.class, false);
    if (isEmailEnabled) {
        sender.setHost(env.getRequiredProperty("email.host"));
        sender.setPort(env.getRequiredProperty("email.port", Integer.class));
    } 
    
    Boolean useCredentials = env.getProperty("email.useCredentials", Boolean.class);
    if (Boolean.TRUE.equals(useCredentials)) {
        sender.setUsername(env.getProperty("email.username"));
        sender.setPassword(env.getProperty("email.password"));
    }
    
    Boolean emailTLS = env.getProperty("email.tls", Boolean.class);
    if (emailTLS != null) {
      sender.getJavaMailProperties().setProperty("mail.smtp.starttls.enable", emailTLS.toString());
    }
    
    return sender;
}
 
Example #18
Source File: DefaultEmailServiceContextBasedTest.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(templateService.mergeTemplateIntoString(anyString(), any(Map.class)))
            .thenReturn("<!doctype html>\n" +
                    "<html>\n" +
                    "<body>\n" +
                    "<p>\n" +
                    "    THIS IS A TEST WITH TEMPLATE\n" +
                    "</p>\n" +
                    "</body>\n" +
                    "</html>");

    ServerSetup serverSetup = new ServerSetup(MAIL_PORT, (String) null, "smtp");
    testSmtp = new GreenMail(serverSetup);
    testSmtp.start();

    //don't forget to set the test port!
    ((JavaMailSenderImpl) javaMailSender).setPort(serverSetup.getPort());
    ((JavaMailSenderImpl) javaMailSender).setHost("localhost");
}
 
Example #19
Source File: SshdShellAutoConfigurationTest.java    From sshd-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testHealthInfoCommand() {
    int smtpPort = SocketUtils.findAvailableTcpPort();
    ServerSetup setup = new ServerSetup(smtpPort, null, ServerSetup.PROTOCOL_SMTP);
    setup.setServerStartupTimeout(5000);
    GreenMail mailServer = new GreenMail(setup);
    JavaMailSenderImpl jmsi = (JavaMailSenderImpl) mailSender;
    mailServer.setUser(jmsi.getUsername(), jmsi.getPassword());
    mailServer.start();
    jmsi.setPort(smtpPort);
    sshCallShell((is, os) -> {
        write(os, "health info");
        verifyResponseContains(is, "{\r\n  \"status\" : \"UP\"");
        mailServer.stop();
    });
}
 
Example #20
Source File: SalespointApplicationConfigurationTests.java    From salespoint with Apache License 2.0 6 votes vote down vote up
@Test
void createsApplicationComponents() {

	assertThat(inventory, is(notNullValue()));
	assertThat(orderManager, is(notNullValue()));
	assertThat(product, is(notNullValue()));
	assertThat(userAccountManager, is(notNullValue()));
	assertThat(businessTime, is(notNullValue()));
	assertThat(authenticationManager, is(notNullValue()));
	assertThat(argumentResolvers, hasSize(1));
	assertThat(initializer, is(not(emptyIterable())));
	assertThat(lineItemFilter, hasSize(1));

	assertThat(mailSender, is(instanceOf(JavaMailSenderImpl.class)));

	JavaMailSenderImpl impl = (JavaMailSenderImpl) mailSender;
	assertThat(impl.getUsername(), is("username"));
	assertThat(impl.getHost(), is("host"));
	assertThat(impl.getPassword(), is("password"));
}
 
Example #21
Source File: MailUtil.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public static JavaMailSenderImpl getMailSender(String _ms) {
	// 读取邮件服务器配置
	String[] configs = getEmailInfos(_ms);
	int port = EasyUtils.obj2Int( ParamConfig.getAttribute(PX.MAIL_SERVER_PORT +_ms , "25") );
	
	JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
	mailSender.setHost( configs[0] );
	mailSender.setPort( port );
	
	if( configs.length == 5 ) {
		mailSender.setUsername( configs[3] );
		mailSender.setPassword( InfoEncoder.simpleDecode(configs[4], 12) ); 
		mailSender.getJavaMailProperties().put("mail.smtp.auth", true);
	}
	
	return mailSender;
}
 
Example #22
Source File: EmailConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);
    
    mailSender.setUsername("[email protected]");
    mailSender.setPassword("password");
    
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "false");
    props.put("mail.debug", "true");
    
    return mailSender;
}
 
Example #23
Source File: MailManager.java    From BlogSystem with Apache License 2.0 6 votes vote down vote up
public MailManager() {
    mailSender = new JavaMailSenderImpl();

    //指定用来发送Email的邮件服务器主机名
    mailSender.setHost("smtp.qq.com");

    //默认端口,标准的SMTP端口
    mailSender.setPort(465);

    Properties properties = new Properties();
    properties.setProperty("mail.host", "smtp.qq.com");
    properties.setProperty("mail.transport.protocol", "smtp");
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.smtp.port", "465");
    properties.setProperty("mail.smtp.socketFactory.port", "465");

    mailSender.setJavaMailProperties(properties);
}
 
Example #24
Source File: AbstractMailService.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get from-address.
 *
 * @param javaMailSender java mail sender.
 * @return from-name internet address
 * @throws UnsupportedEncodingException throws when you give a wrong character encoding
 */
private synchronized InternetAddress getFromAddress(@NonNull JavaMailSender javaMailSender) throws UnsupportedEncodingException {
    Assert.notNull(javaMailSender, "Java mail sender must not be null");

    if (StringUtils.isBlank(this.cachedFromName)) {
        // set personal name
        this.cachedFromName = optionService.getByPropertyOfNonNull(EmailProperties.FROM_NAME).toString();
    }

    if (javaMailSender instanceof JavaMailSenderImpl) {
        // get user name(email)
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) javaMailSender;
        String username = mailSender.getUsername();

        // build internet address
        return new InternetAddress(username, this.cachedFromName, mailSender.getDefaultEncoding());
    }

    throw new UnsupportedOperationException("Unsupported java mail sender: " + javaMailSender.getClass().getName());
}
 
Example #25
Source File: MailComposerImplTest.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * Text template only
 */
@Test
public void testComposeMimeMessageInternalTextVersionOnly() throws MessagingException, IOException, ClassNotFoundException {


    final CacheManager cacheManager = mockery.mock(CacheManager.class);
    final Cache cache = mockery.mock(Cache.class);

    mockery.checking(new Expectations() {{
        allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache));
    }});

    final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager));


    // of course you would use DI in any real-world cases
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
    String textTemplate = "Bender lives in theme park with blackjack poetess";
    String htmlTemplate = null;
    Map<String, byte[]> attachments = Collections.emptyMap();
    MailComposerImpl mailComposer = new MailComposerImpl(null, templates);
    mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test");
    assertTrue(helper.isMultipart());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.getMimeMessage().writeTo(byteArrayOutputStream);
    String str = byteArrayOutputStream.toString("UTF-8");
    assertNotNull(str);
    // html and text present in mail message
    assertTrue(str.contains("Bender lives in theme park with blackjack poetess"));
    mockery.assertIsSatisfied();
}
 
Example #26
Source File: MailClientConverter.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Object> getDefaultValueMappings() {
    Map<String, Object> mappings = super.getDefaultValueMappings();
    mappings.put("host", "localhost");
    mappings.put("port", "2222");
    mappings.put("protocol", JavaMailSenderImpl.DEFAULT_PROTOCOL);
    return mappings;
}
 
Example #27
Source File: MailConfiguration.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #28
Source File: CoreMailConfiguration.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Bean
public JavaMailSender javaMailService() {
    log.debug("javaMailService()");
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

    javaMailSender.setHost(platformMailConfigurationProperties.getHost());
    javaMailSender.setPort(platformMailConfigurationProperties.getPort());
    javaMailSender.setUsername(platformMailConfigurationProperties.getUser().getUsername());
    javaMailSender.setPassword(platformMailConfigurationProperties.getUser().getPassword());

    javaMailSender.setJavaMailProperties(getMailProperties());

    return javaMailSender;
}
 
Example #29
Source File: MailComposerImplTest.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Test
public void testComposeMimeMessageInternalTextAndHtmlVersion() throws MessagingException, IOException, ClassNotFoundException {

    final CacheManager cacheManager = mockery.mock(CacheManager.class);
    final Cache cache = mockery.mock(Cache.class);

    mockery.checking(new Expectations() {{
        allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache));
    }});

    final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager));

    // of course you would use DI in any real-world cases
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
    String textTemplate = "Bender lives in theme park with blackjack poetess";
    String htmlTemplate = "<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>";
    Map<String, byte[]> attachments = Collections.emptyMap();
    MailComposerImpl mailComposer = new MailComposerImpl(null, templates);
    mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test");
    assertTrue(helper.isMultipart());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.getMimeMessage().writeTo(byteArrayOutputStream);
    String str = byteArrayOutputStream.toString("UTF-8");
    assertNotNull(str);
    // html and text present in mail message
    assertTrue(str.contains("Bender lives in theme park with blackjack poetess"));
    assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"));
    mockery.assertIsSatisfied();
}
 
Example #30
Source File: MailComposerImplTest.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Test
public void testComposeMimeMessageInternalTextAndHtmlVersionWithAttach() throws MessagingException, IOException, ClassNotFoundException {

    final CacheManager cacheManager = mockery.mock(CacheManager.class);
    final Cache cache = mockery.mock(Cache.class);

    mockery.checking(new Expectations() {{
        allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache));
    }});

    final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager));

    // of course you would use DI in any real-world cases
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost("localhost");
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
    String textTemplate = "Bender lives in theme park with blackjack poetess";
    String htmlTemplate = "<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>";
    Map<String, byte[]> attachments = Collections.singletonMap("attachment:image/jpeg;myimage.jpg", new byte[]{1, 1, 1});
    MailComposerImpl mailComposer = new MailComposerImpl(null, templates);
    mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test");
    assertTrue(helper.isMultipart());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    helper.getMimeMessage().writeTo(byteArrayOutputStream);
    String str = byteArrayOutputStream.toString("UTF-8");
    assertNotNull(str);
    // html and text present in mail message
    assertTrue(str.contains("Bender lives in theme park with blackjack poetess"));
    assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"));
    // attachment
    assertTrue(str.contains("Content-Type: image/jpeg; name=myimage.jpg"));
    assertTrue(str.contains("Content-Transfer-Encoding: base64"));
    assertTrue(str.contains("Content-Disposition: attachment; filename=myimage.jpg"));
    assertTrue(str.contains("AQEB"));
    mockery.assertIsSatisfied();
}