Java Code Examples for org.springframework.mail.javamail.JavaMailSenderImpl

The following examples show how to use org.springframework.mail.javamail.JavaMailSenderImpl. These examples are extracted from open source projects. 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 Project: halo   Source File: AbstractMailService.java    License: 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 2
Source Project: jsflight   Source File: EmailNotificationService.java    License: 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 3
Source Project: jetlinks-community   Source File: DefaultEmailNotifier.java    License: 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 4
Source Project: open-cloud   Source File: EmailExchanger.java    License: 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 5
Source Project: lemon   Source File: MailServerInfo.java    License: 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 6
Source Project: super-cloudops   Source File: MailMessageNotifier.java    License: 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 Project: halo   Source File: AbstractMailService.java    License: 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 8
Source Project: activiti6-boot2   Source File: EmailConfiguration.java    License: 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 9
Source Project: boubei-tss   Source File: MailUtil.java    License: 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 10
Source Project: boubei-tss   Source File: MailUtil.java    License: Apache License 2.0 6 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 11
Source Project: BlogSystem   Source File: MailManager.java    License: 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 12
@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 13
@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 14
Source Project: yugong   Source File: MailAlarmService.java    License: 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 15
Source Project: pinpoint   Source File: SpringSmtpMailSender.java    License: 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 16
Source Project: alf.io   Source File: SmtpMailer.java    License: 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 17
@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 18
Source Project: shark   Source File: SendMail.java    License: 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 19
@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 20
Source Project: tutorials   Source File: EmailConfiguration.java    License: 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 21
@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 22
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 23
Source Project: cia   Source File: EmailServiceImpl.java    License: 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 24
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 25
Source Project: seppb   Source File: JavaMailUtilsTest.java    License: MIT License 5 votes vote down vote up
@Before
public void before() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setPort(25);
    javaMailSender.setHost("mail.purang.com");
    javaMailSender.setPassword("Purang123");
    javaMailSender.setUsername("[email protected]");
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", String.valueOf(true));
    properties.setProperty("mail.smtp.starttls.enable", String.valueOf(true));
    properties.setProperty("mail.smtp.starttls.required", String.valueOf(true));
    mailDTO.setTo(new String[]{"[email protected]"});
    mailDTO.setSubject("test");
    mailDTO.setHtml(false);
    mailDTO.setFailRetry(true);
    mailDTO.setContent("test mail");
    mailDTO.setFailTo(new String[]{"[email protected]"});
    mailDTO.setFailSubject("failed mail");
    mailDTO.setFailRetryTime(10 * 1000);
    mailDTO.setFailRetryCount(3);
    mailDTO.setFrom("[email protected]");
    PowerMockito.mockStatic(CommonFactory.class);
    PowerMockito.when(CommonFactory.getApplicationContext()).thenReturn(ac);
    javaMailSender.setJavaMailProperties(properties);
    when(ac.getBean(JavaMailSender.class)).thenReturn(javaMailSender);

}
 
Example 26
Source Project: open-cloud   Source File: EmailSender.java    License: MIT License 5 votes vote down vote up
/**
 * 发送邮件
 */
public void sendSimpleMail(JavaMailSenderImpl javaMailSender, EmailMessage emailMessage) throws Exception {
    MimeMessage message = null;
    message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(emailMessage.getTo());
    if (emailMessage.getCc() != null && emailMessage.getCc().length > 0) {
        helper.setCc(emailMessage.getCc());
    }
    helper.setFrom(javaMailSender.getUsername());
    helper.setSubject(emailMessage.getSubject());
    helper.setText(emailMessage.getContent(), true);
    this.addAttachment(helper, emailMessage);
    javaMailSender.send(message);
}
 
Example 27
@Test
void testCreateMailSenderWithDefaultProperties() {
  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("true", actualProperties.getProperty(MAIL_SMTP_STARTTLS_ENABLE));
  assertEquals("false", actualProperties.getProperty(MAIL_SMTP_QUITWAIT));
  assertEquals("true", actualProperties.getProperty(MAIL_SMTP_AUTH));
  assertEquals("[email protected]", actualProperties.getProperty(MAIL_SMTP_FROM_ADDRESS));
}
 
Example 28
Source Project: DimpleBlog   Source File: EmailServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendHtmlMail(String to, String title, String content) {
    EmailSetting emailSetting = configService.selectConfigByConfigKey(ConfigKey.CONFIG_KEY_EMAIL_SETTING, EmailSetting.class);
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setUsername(emailSetting.getUser());
    mailSender.setHost(emailSetting.getHost());
    mailSender.setDefaultEncoding("utf-8");
    mailSender.setPassword(emailSetting.getPassword());
    mailSender.setPort(emailSetting.getPort());

    Properties properties = new Properties();
    properties.put("mail.smtp.host", emailSetting.getHost());
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
    properties.put("mail.smtp.port", emailSetting.getPort());
    properties.put("mail.smtp.socketFactory.port", emailSetting.getPort());
    properties.put("mail.smtp.ssl.enable", true);
    Session session = Session.getInstance(properties);

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(emailSetting.getFromEmail());
        mimeMessageHelper.setTo(to);
        if (StringUtils.isNotEmpty(emailSetting.getStationmasterEmail())) {
            mimeMessageHelper.setBcc(emailSetting.getStationmasterEmail());
        }
        mimeMessageHelper.setSubject(title);
        mimeMessageHelper.setText(content, true);
        mailSender.setSession(session);
        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
       log.error(e.getMessage(), e);
    }
}
 
Example 29
Source Project: halo   Source File: MailSenderFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get mail sender.
 *
 * @param mailProperties mail properties must not be null
 * @return java mail sender
 */
@NonNull
public JavaMailSender getMailSender(@NonNull MailProperties mailProperties) {
    Assert.notNull(mailProperties, "Mail properties must not be null");

    // create mail sender
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    // set properties
    setProperties(mailSender, mailProperties);

    return mailSender;
}
 
Example 30
Source Project: halo   Source File: MailSenderFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void setProperties(@NonNull JavaMailSenderImpl mailSender, @NonNull MailProperties mailProperties) {
    mailSender.setHost(mailProperties.getHost());
    mailSender.setPort(mailProperties.getPort());
    mailSender.setUsername(mailProperties.getUsername());
    mailSender.setPassword(mailProperties.getPassword());
    mailSender.setProtocol(mailProperties.getProtocol());
    mailSender.setDefaultEncoding(mailProperties.getDefaultEncoding().name());

    if (!CollectionUtils.isEmpty(mailProperties.getProperties())) {
        Properties properties = new Properties();
        properties.putAll(mailProperties.getProperties());
        mailSender.setJavaMailProperties(properties);
    }
}