用Java发送Email就这么简单

咱程序员在开发过程中,时常会遇到需要发送邮件的场景,好比通知用户注册成功、提醒密码找回啥的。这时候,Java就派上大用场啦,今儿个咱就唠唠咋用Java发送Email。

一、准备工作

要实现Java发送邮件,咱得先引入相关的依赖。要是用Maven构建项目,在pom.xml文件里加上这几行代码:


    javax.mail
    mail
    1.4.7


    javax.activation
    activation
    1.1.1

这就好比给你的“Java战车”装上了专门发送邮件的“武器模块”,有了它们,才能顺利开展后续工作。

二、简单文本邮件发送

咱先从发送简单的文本邮件开始。下面这段代码就是实现这一功能的“秘密武器”:

 
  
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SimpleEmailSender {
    public static void main(String[] args) {
        // 邮件服务器的属性配置
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.example.com");
        properties.put("mail.smtp.port", "587");

        // 发件人的邮箱账号和密码
        String senderEmail = "[email protected]";
        String senderPassword = "your_password";

        // 创建一个会话对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            // 创建一个邮件消息对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
            message.setSubject("这是一封Java发送的测试邮件");
            message.setText("嘿,这封邮件是通过Java代码发送的哦,是不是很有意思!");

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败!");
        }
    }
}

在这段代码里,咱先设置了邮件服务器的相关属性,像是否需要认证、服务器地址和端口啥的。然后创建了一个会话,通过这个会话来创建邮件消息对象。在邮件消息对象里,设置好发件人、收件人、主题和邮件内容,最后调用Transport.send(message)方法把邮件发送出去。要是一切顺利,控制台就会打印“邮件发送成功!”,要是出问题了,就会打印错误信息。

三、发送带附件的邮件

有时候,光发文本可不够,咱还得带上附件。这也不难,看下面的代码:

 
  
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

public class AttachmentEmailSender {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.example.com");
        properties.put("mail.smtp.port", "587");

        String senderEmail = "[email protected]";
        String senderPassword = "your_password";

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(senderEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
            message.setSubject("这是一封带附件的Java邮件");

            // 创建一个多重消息部分的对象
            Multipart multipart = new MimeMultipart();

            // 创建一个文本部分
            BodyPart textPart = new MimeBodyPart();
            textPart.setText("嘿,这封邮件带有附件哦,请注意查收!");
            multipart.addBodyPart(textPart);

            // 创建一个附件部分
            BodyPart attachmentPart = new MimeBodyPart();
            File file = new File("path/to/your/file.pdf");
            attachmentPart.attachFile(file);
            multipart.addBodyPart(attachmentPart);

            // 将多重消息部分设置到邮件消息中
            message.setContent(multipart);

            Transport.send(message);
            System.out.println("带附件的邮件发送成功!");
        } catch (MessagingException | java.io.IOException e) {
            e.printStackTrace();
            System.out.println("带附件的邮件发送失败!");
        }
    }
}

这段代码里,除了文本部分,咱又创建了一个附件部分。通过MimeBodyPartattachFile方法把文件添加为附件,再把文本部分和附件部分都添加到Multipart对象里,最后设置到邮件消息中发送出去。这样,收件人就能收到带附件的邮件啦。

怎么样,用Java发送邮件是不是也没那么难?只要掌握了这些方法,以后在项目里实现邮件发送功能,那还不是手到擒来!大家赶紧动手试试吧!

你可能感兴趣的:(业务系统应用技术,java,前端)