Last active
August 30, 2021 21:36
-
-
Save hakimkal/9f36a12dfaacc762299ec11643790582 to your computer and use it in GitHub Desktop.
Akka Typed Actor for sending email using Courier library
This file contains hidden or 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
| object EmailService { | |
| case class EmailModel(toEmail: String, subject: String, body: String) | |
| sealed trait Command | |
| case class SendEmailCommand(email: EmailModel, replyTo: ActorRef[Response]) extends Command { | |
| def sendEmail(email: EmailModel): Future[Unit] = { | |
| val mailer = | |
| Mailer(Config.smtpHost, Config.smtpPort) | |
| .auth(true) | |
| .as(Config.smtpUser, Config.smtpPassword) | |
| .startTls(true)() | |
| val envelope = Envelope | |
| .from(new InternetAddress("[email protected]")) | |
| .to(new InternetAddress(email.toEmail)) | |
| .subject(email.subject) | |
| .content(Multipart().html(email.body)) | |
| mailer(envelope) | |
| } | |
| } | |
| sealed trait Response | |
| case class SendEmailResponse(email: String) extends Response | |
| case class ErrorResponse(message: String) extends Response | |
| def apply(): Behavior[Command] = | |
| Behaviors.receive({ (context, message) => | |
| val log = context.log | |
| message match { | |
| case req: SendEmailCommand => | |
| { | |
| req.sendEmail(req.email).onComplete { | |
| case Success(_) => | |
| req.replyTo ! SendEmailResponse(req.email.toEmail) | |
| case Failure(ex) => | |
| req.replyTo ! ErrorResponse("Error Occured " + ex.getMessage) | |
| } | |
| } | |
| Behaviors.same | |
| } | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment