Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sending mails fluently in Scala
package object mail {
implicit def stringToSeq(single: String): Seq[String] = Seq(single)
implicit def liftToOption[T](t: T): Option[T] = Some(t)
sealed abstract class MailType
case object Plain extends MailType
case object Rich extends MailType
case object MultiPart extends MailType
case class Mail(
from: (String, String), // (email -> name)
to: Seq[String],
cc: Seq[String] = Seq.empty,
bcc: Seq[String] = Seq.empty,
subject: String,
message: String,
richMessage: Option[String] = None,
attachment: Option[(java.io.File)] = None
)
object send {
def a(mail: Mail) {
import org.apache.commons.mail._
val format =
if (mail.attachment.isDefined) MultiPart
else if (mail.richMessage.isDefined) Rich
else Plain
val commonsMail: Email = format match {
case Plain => new SimpleEmail().setMsg(mail.message)
case Rich => new HtmlEmail().setHtmlMsg(mail.richMessage.get).setTextMsg(mail.message)
case MultiPart => {
val attachment = new EmailAttachment()
attachment.setPath(mail.attachment.get.getAbsolutePath)
attachment.setDisposition(EmailAttachment.ATTACHMENT)
attachment.setName(mail.attachment.get.getName)
new MultiPartEmail().attach(attachment).setMsg(mail.message)
}
}
// TODO Set authentication from your configuration, sys properties or w/e
// Can't add these via fluent API because it produces exceptions
mail.to foreach (commonsMail.addTo(_))
mail.cc foreach (commonsMail.addCc(_))
mail.bcc foreach (commonsMail.addBcc(_))
commonsMail.
setFrom(mail.from._1, mail.from._2).
setSubject(mail.subject).
send()
}
}
}
package something
object Demo {
import mail._
send a new Mail (
from = ("john.smith@mycompany.com", "John Smith"),
to = "boss@mycompany.com",
cc = "hr@mycompany.com",
subject = "Import stuff",
message = "Dear Boss..."
)
send a new Mail (
from = "john.smith@mycompany.com" -> "John Smith",
to = Seq("dev@mycompany.com", "marketing@mycompany.com"),
subject = "Our New Strategy (tm)",
message = "Please find attach the latest strategy document.",
richMessage = "Here's the <blink>latest</blink> <strong>Strategy</strong>..."
)
send a new Mail (
from = "john.smith@mycompany.com" -> "John Smith",
to = "dev@mycompany.com" :: "marketing@mycompany.com" :: Nil,
subject = "Our 5-year plan",
message = "Here is the presentation with the stuff we're going to for the next five years.",
attachment = new java.io.File("/home/boss/important-presentation.ppt")
)
}
@Dinduks

This comment has been minimized.

Show comment
Hide comment
@Dinduks

Dinduks Mar 4, 2014

Thank you for sharing this.

Dinduks commented Mar 4, 2014

Thank you for sharing this.

@MMMarcy

This comment has been minimized.

Show comment
Hide comment
@MMMarcy

MMMarcy Dec 22, 2014

Thanks man, really appreciate

MMMarcy commented Dec 22, 2014

Thanks man, really appreciate

@ghost

This comment has been minimized.

Show comment
Hide comment
@ghost

ghost Mar 20, 2015

Thank you for sharing this

ghost commented Mar 20, 2015

Thank you for sharing this

@hraban

This comment has been minimized.

Show comment
Hide comment
@hraban

hraban Mar 31, 2015

Hi, thanks for sharing. What's the license on this code? Can it be used in commercial projects?

hraban commented Mar 31, 2015

Hi, thanks for sharing. What's the license on this code? Can it be used in commercial projects?

@thiloplanz

This comment has been minimized.

Show comment
Hide comment
@thiloplanz

thiloplanz Oct 9, 2015

Can you add a license header?

thiloplanz commented Oct 9, 2015

Can you add a license header?

@schon

This comment has been minimized.

Show comment
Hide comment
@schon

schon Oct 26, 2015

Thank you for sharing this

schon commented Oct 26, 2015

Thank you for sharing this

@azickh

This comment has been minimized.

Show comment
Hide comment
@azickh

azickh Jan 22, 2016

Hi, I'm posting html, but get html content like attachments. What is the problem?

val html = """<html>Thanks for Joining!
               |You’re going to love Gifty.uz
               |
               |To complete your registration for ***, please <a href="http://mydomain.com/somepath">confirm</a> your email.
               |
               |Need help? Have feedback? Feel free to contact us</html>""".stripMargin

send a new Mail(
  from = mynoreply@gmail.com -> "noreplay",
  to = Seq("myrcpt@gmail.com"),
  subject = "Some subject",
  message = "Some plain content",
  richMessage = html
)

Thanks, Aziz

azickh commented Jan 22, 2016

Hi, I'm posting html, but get html content like attachments. What is the problem?

val html = """<html>Thanks for Joining!
               |You’re going to love Gifty.uz
               |
               |To complete your registration for ***, please <a href="http://mydomain.com/somepath">confirm</a> your email.
               |
               |Need help? Have feedback? Feel free to contact us</html>""".stripMargin

send a new Mail(
  from = mynoreply@gmail.com -> "noreplay",
  to = Seq("myrcpt@gmail.com"),
  subject = "Some subject",
  message = "Some plain content",
  richMessage = html
)

Thanks, Aziz

@ghost

This comment has been minimized.

Show comment
Hide comment
@ghost

ghost May 31, 2016

This is awesome

ghost commented May 31, 2016

This is awesome

@futureage

This comment has been minimized.

Show comment
Hide comment
@futureage

futureage Sep 21, 2016

Thank you for sharing this

futureage commented Sep 21, 2016

Thank you for sharing this

@prayagupd

This comment has been minimized.

Show comment
Hide comment
@prayagupd

prayagupd Jan 10, 2017

this is so fluent. thanks @mariussoutier

prayagupd commented Jan 10, 2017

this is so fluent. thanks @mariussoutier

@tusharbabbar

This comment has been minimized.

Show comment
Hide comment
@tusharbabbar

tusharbabbar Feb 3, 2017

Beautifully written. Thanks. 👍

tusharbabbar commented Feb 3, 2017

Beautifully written. Thanks. 👍

@kwidjaja1312

This comment has been minimized.

Show comment
Hide comment
@kwidjaja1312

kwidjaja1312 Jun 7, 2017

Thanks a lot

kwidjaja1312 commented Jun 7, 2017

Thanks a lot

@ammills01

This comment has been minimized.

Show comment
Hide comment
@ammills01

ammills01 Oct 27, 2017

Thanks for sharing!

ammills01 commented Oct 27, 2017

Thanks for sharing!

@gawalimangesh007

This comment has been minimized.

Show comment
Hide comment
@gawalimangesh007

gawalimangesh007 Jan 7, 2018

Hi mariussoutier, I am getting below error

Exception in thread "main" org.apache.commons.mail.EmailException: Cannot find valid hostname for mail session
at org.apache.commons.mail.Email.getMailSession(Email.java:639)
at org.apache.commons.mail.Email.buildMimeMessage(Email.java:1278)
at org.apache.commons.mail.Email.send(Email.java:1447)
at Mail.package$send$.a(mail.scala:59)
at Seal_Phy$.main(Seal_Phy.scala:173)
at Seal_Phy.main(Seal_Phy.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

gawalimangesh007 commented Jan 7, 2018

Hi mariussoutier, I am getting below error

Exception in thread "main" org.apache.commons.mail.EmailException: Cannot find valid hostname for mail session
at org.apache.commons.mail.Email.getMailSession(Email.java:639)
at org.apache.commons.mail.Email.buildMimeMessage(Email.java:1278)
at org.apache.commons.mail.Email.send(Email.java:1447)
at Mail.package$send$.a(mail.scala:59)
at Seal_Phy$.main(Seal_Phy.scala:173)
at Seal_Phy.main(Seal_Phy.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:738)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

@dsjayakar

This comment has been minimized.

Show comment
Hide comment
@dsjayakar

dsjayakar Feb 6, 2018

You need to set email server hostname by commonsMail.setHostName("your email server host")

dsjayakar commented Feb 6, 2018

You need to set email server hostname by commonsMail.setHostName("your email server host")

@larsjaas

This comment has been minimized.

Show comment
Hide comment
@larsjaas

larsjaas Mar 3, 2018

Tiny nit: The example should be attachment = Some(new java.io.File(...))

larsjaas commented Mar 3, 2018

Tiny nit: The example should be attachment = Some(new java.io.File(...))

@amuradyan

This comment has been minimized.

Show comment
Hide comment
@amuradyan

amuradyan Jun 20, 2018

Thanks a lot man

amuradyan commented Jun 20, 2018

Thanks a lot man

@RezaBidar

This comment has been minimized.

Show comment
Hide comment
@RezaBidar

RezaBidar Jul 11, 2018

sample for gmail and multi file support

package object Mail {

  implicit def stringToSeq(single: String): Seq[String] = Seq(single)
  implicit def liftToOption[T](t: T): Option[T] = Some(t)

  sealed abstract class MailType
  case object Plain extends MailType
  case object Rich extends MailType
  case object MultiPart extends MailType

  case class Mail(
                   from: (String, String), // (email -> name)
                   to: Seq[String],
                   cc: Seq[String] = Seq.empty,
                   bcc: Seq[String] = Seq.empty,
                   subject: String,
                   message: String,
                   richMessage: Option[String] = None,
                   attachments: Seq[(java.io.File)] = Seq.empty
                 )

  object send {
    def a(mail: Mail) {
      import org.apache.commons.mail._

      val format =
        if (mail.attachments.nonEmpty) MultiPart
        else if (mail.richMessage.isDefined) Rich
        else Plain

      val commonsMail: Email = format match {
        case Plain => new SimpleEmail().setMsg(mail.message)
        case Rich => new HtmlEmail().setHtmlMsg(mail.richMessage.get).setTextMsg(mail.message)
        case MultiPart => {
          val multipartEmail = new MultiPartEmail()
          mail.attachments.foreach { file =>
            val attachment = new EmailAttachment()
            attachment.setPath(file.getAbsolutePath)
            attachment.setDisposition(EmailAttachment.ATTACHMENT)
            attachment.setName(file.getName)
            multipartEmail.attach(attachment)
          }
          multipartEmail.setMsg(mail.message)
        }
      }

      // TODO Set authentication from your configuration, sys properties or w/e

      // Can't add these via fluent API because it produces exceptions
      mail.to foreach (commonsMail.addTo(_))
      mail.cc foreach (commonsMail.addCc(_))
      mail.bcc foreach (commonsMail.addBcc(_))

      // gmail config
      commonsMail.setHostName("smtp.googlemail.com")
      commonsMail.setAuthentication("email","pass")
      commonsMail.setSSLOnConnect(true)
      commonsMail.setSmtpPort(465)

      commonsMail.
        setFrom(mail.from._1, mail.from._2).
        setSubject(mail.subject).
        send()
    }
  }
}

RezaBidar commented Jul 11, 2018

sample for gmail and multi file support

package object Mail {

  implicit def stringToSeq(single: String): Seq[String] = Seq(single)
  implicit def liftToOption[T](t: T): Option[T] = Some(t)

  sealed abstract class MailType
  case object Plain extends MailType
  case object Rich extends MailType
  case object MultiPart extends MailType

  case class Mail(
                   from: (String, String), // (email -> name)
                   to: Seq[String],
                   cc: Seq[String] = Seq.empty,
                   bcc: Seq[String] = Seq.empty,
                   subject: String,
                   message: String,
                   richMessage: Option[String] = None,
                   attachments: Seq[(java.io.File)] = Seq.empty
                 )

  object send {
    def a(mail: Mail) {
      import org.apache.commons.mail._

      val format =
        if (mail.attachments.nonEmpty) MultiPart
        else if (mail.richMessage.isDefined) Rich
        else Plain

      val commonsMail: Email = format match {
        case Plain => new SimpleEmail().setMsg(mail.message)
        case Rich => new HtmlEmail().setHtmlMsg(mail.richMessage.get).setTextMsg(mail.message)
        case MultiPart => {
          val multipartEmail = new MultiPartEmail()
          mail.attachments.foreach { file =>
            val attachment = new EmailAttachment()
            attachment.setPath(file.getAbsolutePath)
            attachment.setDisposition(EmailAttachment.ATTACHMENT)
            attachment.setName(file.getName)
            multipartEmail.attach(attachment)
          }
          multipartEmail.setMsg(mail.message)
        }
      }

      // TODO Set authentication from your configuration, sys properties or w/e

      // Can't add these via fluent API because it produces exceptions
      mail.to foreach (commonsMail.addTo(_))
      mail.cc foreach (commonsMail.addCc(_))
      mail.bcc foreach (commonsMail.addBcc(_))

      // gmail config
      commonsMail.setHostName("smtp.googlemail.com")
      commonsMail.setAuthentication("email","pass")
      commonsMail.setSSLOnConnect(true)
      commonsMail.setSmtpPort(465)

      commonsMail.
        setFrom(mail.from._1, mail.from._2).
        setSubject(mail.subject).
        send()
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment