Created
March 8, 2019 04:55
-
-
Save manish-in-java/c71e974fa178d3cdaf51bb4dd8f61aec to your computer and use it in GitHub Desktop.
SMTP Connection Pooling with Spring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.mail.internet.MimeMessage; | |
import org.nlab.smtp.pool.SmtpConnectionPool; | |
import org.nlab.smtp.transport.connection.ClosableSmtpConnection; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Service; | |
@Service | |
public class EmailService { | |
@Autowired | |
private SmtpConnectionPool smtpConnectionPool; | |
public void sendEmail() { | |
try (ClosableSmtpConnection transport = smtpConnectionPool.borrowObject()) { | |
MimeMessage mimeMessage = new MimeMessage(transport.getSession()); | |
... | |
transport.sendMessage(mimeMessage); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Properties; | |
import javax.mail.Session; | |
import org.nlab.smtp.pool.SmtpConnectionPool; | |
import org.nlab.smtp.transport.factory.SmtpConnectionFactory; | |
import org.nlab.smtp.transport.factory.SmtpConnectionFactoryBuilder; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
@Configuration | |
public class SMTPConfiguration { | |
@Bean | |
public SmtpConnectionFactory smtpConnectionFactory() { | |
return SmtpConnectionFactoryBuilder.newSmtpBuilder() | |
.session(smtpSession()) | |
.protocol(...) | |
.host(...) | |
.port(...) | |
.username(...) | |
.password(...) | |
.build(); | |
} | |
@Bean | |
public SmtpConnectionPool smtpConnectionPool() { | |
return new SmtpConnectionPool(SmtpConnectionFactoryBuilder.newSmtpBuilder().build()); | |
} | |
@Bean | |
public Properties smtpProperties() { | |
Properties properties = new Properties(); | |
properties..put("mail.smtp.host", ...); | |
properties..put("mail.smtp.port", ...); | |
return properties; | |
} | |
@Bean | |
public Session smtpSession() { | |
return Session.getDefaultInstance(smtpProperties(), null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm facing the problem while integrate with Spring boot application. Please help me to resolve the problem.
https://stackoverflow.com/questions/63722608/spring-boot-with-smtp-connection-pool