已复制
全屏展示
复制代码

Scala发送邮件完整示例


· 3 min read

一. pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>email_sender</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.11.12</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.15.2</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/*.scala</include>
                                <include>**/*.java</include>
                            </includes>
                        </configuration>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

二. 发送代码

以网易的 yeah.net 邮箱为例,注意有些邮箱的密码是授权码。

package org.example

import javax.mail.internet.{InternetAddress, MimeBodyPart, MimeMessage, MimeMultipart}
import javax.mail.{Address, Message, PasswordAuthentication, Session, Transport};

object EmailSender {
  def main(args: Array[String]): Unit = {
    val from = "usernamexx@yeah.net" // 发件人邮箱
    val password = "xxxx"            // 发件人邮箱密码,注意:有些邮箱是是授权码
    val to = "xxxxx@qq.com"          // 收件人邮箱

    val properties = new java.util.Properties()
    properties.put("mail.smtp.host", "smtp.yeah.net") // 使用 SMTP 服务器
    properties.put("mail.smtp.port", "465")           // 使用 SMTP 端口号
    properties.put("mail.smtp.timeout", "10000")      // 超时 毫秒
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.ssl.enable", "true")

    val session = Session.getInstance(properties, new javax.mail.Authenticator {
      override def getPasswordAuthentication: PasswordAuthentication = {
        new PasswordAuthentication(from, password)
      }
    })

    try {
      val message = new MimeMessage(session)
      message.setFrom(new InternetAddress(from))
      message.setRecipients(Message.RecipientType.TO, Array[Address](new InternetAddress(to)))
      message.setSubject("这是一封测试邮件") // 邮件标题

      // 创建一个 Multipart 对象,用于组合文本和附件
      val multipart = new MimeMultipart()

      // 创建文本部分
      val textPart = new MimeBodyPart()
      textPart.setText("这是邮件的纯文本正文")
      multipart.addBodyPart(textPart)

      // 创建 HTML 部分
      val htmlPart = new MimeBodyPart()
      htmlPart.setContent("<h1>这是邮件的 HTML 正文</h1>", "text/html;charset=utf-8")
      multipart.addBodyPart(htmlPart)

      // 添加附件 1
      val attachment1 = new MimeBodyPart()
      attachment1.attachFile("/Users/yzy/.bash_profile")
      multipart.addBodyPart(attachment1)

      // 添加附件 2
      val attachment2 = new MimeBodyPart()
      attachment2.attachFile("/etc/profile")
      multipart.addBodyPart(attachment2)

      // 将 Multipart 对象设置为消息内容
      message.setContent(multipart)

      // 发送邮件
      println("开始发送邮件...")
      Transport.send(message)
      println("邮件发送成功!")

    } catch {
      case e: Exception =>
        println("邮件发送失败!")
        e.printStackTrace()
    }
  }
}

三. 打包发送

[yzy@yzym email_sender]$ mvn clean package
[yzy@yzym email_sender]$ java -cp target/email_sender-1.0-SNAPSHOT-jar-with-dependencies.jar org.example.EmailSender
开始发送邮件...
邮件发送成功!

🔗

文章推荐