邮件内容以表格形式展现
import com.typesafe.config.ConfigFactory
import play.api.libs.mailer._
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* 发送email
*/
object EmailUtil {
def sendEmail(ehost: String,
eport: Int,
euser: String,
epassword: String,
subject: String,
content: List[List[String]],
to: Seq[String]): Unit = {
val from: String = euser //填写邮件发送地址
val currentTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分")
val formattedTime = currentTime.format(formatter)
var emailText = ""
content.foreach {
con =>
emailText +=
s"""|<tr>
|<td>${con.head}</td>
|<td>${con(1)}</td>
|<td>${con(2)}</td>
|</tr> \n"""
}
val bodyHtml: Option[String] = Option(
s"""
|<html>
|<head>
|<style>
| table {
| width: 100%;
| border-collapse: collapse;
| }
| th, td {
| border: 1px solid black;
| padding: 8px;
| text-align: left;
| }
| th {
| background-color: lightblue;
| }
| .indented-text {
| text-indent: 2em;
| }
|</style>
|</head>
|<body>
|<br />
|<p align="left">各位领导:</p>
|<p align="left" class="indented-text">您们好!${formattedTime}推送任务执行情况如下:</p>
|<table border="1px red solid" cellspacing="0">
|<tr>
|<th>任务名</th>
|<th>任务执行状态</th>
|<th>任务推送结果</th>
|</tr>
${emailText}
|</table>
|<br />
|<br />
|<hr>
|</body>
|</html>
""".stripMargin)
val charset: Option[String] = Option("utf-8") // 字符编码 默认utf-8
// 生成邮件
val email: Email = Email(subject, from, to, None, bodyHtml, charset)
// STMP服务参数
val host: String = ehost
// STMP服务端口号
val port: Int = eport
// STMP服务发送者用户邮箱
val user: Option[String] = Option(euser)
// 在126网站中开通smtp服务,会返回一个密码
// 这个密码很重要,填错了发不了邮件
val password: Option[String] = Option(epassword)
val timeout: Option[Int] = Option(10000)
//setSocketTimeout 默认60s
val connectionTimeout: Option[Int] = Option(10000)
//setSocketConnectionTimeout 默认60s
// STMP服务SMTPConfiguration
val configuration: SMTPConfiguration = new SMTPConfiguration(
host, port, false, false, false,
user, password, false, timeout,
connectionTimeout, ConfigFactory.empty(), false)
val mailer: SMTPMailer = new SMTPMailer(configuration)
// 发送邮件
mailer.send(email)
}
}
逐行读取文件内容并发送邮件
import com.Utils.{EmailUtil, propertiesUtil}
import java.util.Properties
import scala.io.Source
object JobStateEmail {
def main(args: Array[String]): Unit = {
val filePath: String = args(0)
val prop: Properties = propertiesUtil.getProperties(filePath)
val emailHost: String = prop.getProperty("emailHost")
val emailPort: Int = prop.getProperty("emailPort").toInt
val emailUser: String = prop.getProperty("emailUser")
val emailPassword: String = prop.getProperty("emailPassword")
val sendemail: String = prop.getProperty("sendemail")
val to= sendemail.split(",").toSeq
val filename: String = args(1)
val subject: String = args(2)
val lines = Source.fromFile(filename).getLines().toList
val content = lines.map(line => line.split(",").toList)
EmailUtil.sendEmail(emailHost, emailPort, emailUser, emailPassword, subject, content, to)
}
}