I register the below bean in the appconfig. How to use this bean using constructor injection in my service? I need to pass the userid, password dynamically.
@Bean
public JavaMailSender getMailSender(JavaMailerDTO javaMailer){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setJavaMailProperties(mailProperties(javaMailer));
mailSender.setHost(javaMailer.getHost());
mailSender.setUsername(javaMailer.getEmailId());
mailSender.setPassword(javaMailer.getEmailPassword());
mailSender.setPort(Integer.parseInt(javaMailer.getPort()));
return mailSender;
}
private Properties mailProperties(JavaMailerDTO javaMailer){
Properties properties = new Properties();
properties.put(ApplicationConstant.MAIL_AUTH, ApplicationConstant.TRUE);
// .....
properties.put(ApplicationConstant.MAIL_SMTPPORT,javaMailer.getPort());
return properties;
}
Could you please help me to send email using above bean autowiring?
I would suggest you to create a factory which will build for you a separate instance JavaMailSender for different credentials.
Something like this:
public interface MailSenderFactory {
JavaMailSender getSender(String email, String password);
}
@Component
public static class MailSenderFactoryImpl implements MailSenderFactory {
private final JavaMailerDTO javaMailer;
@Autowired
public MailSenderFactoryImpl(JavaMailerDTO javaMailer) {
this.javaMailer = javaMailer;
}
@Override
public JavaMailSender getSender(final String email, final String password) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setJavaMailProperties(mailProperties(javaMailer));
mailSender.setHost(javaMailer.getHost());
mailSender.setUsername(email);
mailSender.setPassword(password);
mailSender.setPort(Integer.parseInt(javaMailer.getPort()));
return mailSender;
}
private Properties mailProperties(JavaMailerDTO javaMailer) {
Properties properties = new Properties();
properties.put(ApplicationConstant.MAIL_AUTH, ApplicationConstant.TRUE);
// .....
properties.put(ApplicationConstant.MAIL_SMTPPORT, javaMailer.getPort());
return properties;
}
}
Now you can use it like this:
@Service
public static class MailService {
private final MailSenderFactory mailSenderFactory;
public MailService(MailSenderFactory mailSenderFactory) {
this.mailSenderFactory = mailSenderFactory;
}
public void sendMail() {
JavaMailSender mailSender = mailSenderFactory.getSender("[email protected]", "123456");
mailSender.send(...);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With