java发送邮件

目录

maven依赖

参考

发送给多人

示例代码

发送带附件的邮件


maven依赖

<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.2</version>
</dependency>

参考

Java 发送邮件 | 菜鸟教程

Java实现邮件发送_baolingye的博客-优快云博客_java发送邮件

javax.mail发送邮件(带附件)_chengnounang4197的博客-优快云博客

发送给多人

message.addRecipients(Message.RecipientType.CC,ccAddressList.toArray(new InternetAddress[ccAddressList.size()]));

示例代码

package cn.com.upxcy.springbootmybatis.utils;

import java.util.ArrayList;
import java.util.Properties;
import java.util.List;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSendUtil {

    private static final String smtpHost = "";//smtp服务器地址
    private static final String smtpPort = "";//smtp服务器地址

    public static void sendMail(String title, String article, String fromAddress, String[] toAddress, String[] ccAddress) {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", smtpHost);
        properties.setProperty("mail.smtp.port", smtpPort);
        Session session = Session.getDefaultInstance(properties);
        try {
            MimeMessage message = new MineMessage(session);
            message.setSubject(title); //主题
            message.setText(article);  //内容
            message.setFrom(new InternetAddress(fromAddress)); //发送方

            List<InternetAddress> toAddressList = new ArrayList<>();
            for (String addressStr : toAddressList) {
                InternetAddress address = new InternetAddress(addressStr);
                toAddressList.add(address);
            }

            message.addRecipients(Message.RecipientType.TO, toAddressList.toArray(new InternetAddress(toAddressList.size()))); //接收方

            if (ccAddress != null) {
                List<InternetAddress> ccAddressList = new ArrayList<>();
                for (String addressStr : ccAddress) {
                    InternetAddress address = new InternetAddress(addressStr);
                    ccAddressList.add(address);
                }
                message.addRecipients(Message.RecipientType.CC, toAddressList.toArray(new InternetAddress(ccAddressList.size()))); //抄送方

                //发送
                messafe.saveChanges();
                Transport.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

发送带附件的邮件

核心:为正文和附件分别创建MimeBodyPart,然后将多个MimeBodyPart添加到MimeMultiPart中

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值