java Mail发送电子邮件的客户端

第一步:引入maven依赖:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

第二步:编写客户端:

package company.email.sendmessage;

import lombok.Data;
import org.springframework.util.StringUtils;

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

/**
 * 发送邮件的工具类
 * @Author csh10609
 *
 */
public class SendMailUtils {

    public static void SendMail(final EmailEntity entity) {

        try {
            Authenticator authenticator = new Authenticator() {
                private PasswordAuthentication authentication;

                {
                    authentication = new PasswordAuthentication(entity.getUserName(), entity.getPassword());
                }

                protected PasswordAuthentication getPasswordAuthentication() {
                    return authentication;
                }
            };

            Session session = Session.getInstance(entity.getProperties(), authenticator);

            Message msg = new MimeMessage(session);

            msg.setSubject(entity.getSubject());

            msg.setText(entity.getText());

            //发件人如果为空,直接返回
            if (StringUtils.isEmpty(entity.getFrom())) {
                return;
            }

            msg.setFrom(new InternetAddress(entity.getFrom()));

            Transport transport = session.getTransport();

            //收件人如果为空,直接返回
            if (StringUtils.isEmpty(entity.getTo())) {
                return;
            }

            transport.send(msg, new Address[]{new InternetAddress(entity.getTo())});

            transport.close();

            //System.out.println("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 邮件的参数信息
     */
    @Data
    public static class EmailEntity{
        //邮箱的配置信息
        private Properties properties;
        //邮箱用户名
        private String userName;
        //邮箱密码
        private String password;
        //主题
        private String subject;
        //邮件内容
        private String text;
        //发件人
        private String from;
        //收件人
        private String to;
    }


    public static void main(String[] args) {
        EmailEntity entity = new EmailEntity();
        Properties props = new Properties();
        props.setProperty("mail.debug", "true");
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.host", "smtp.baozun.com");
        props.setProperty("mail.transport.protocol", "smtp");
        entity.setProperties(props);
        entity.setUserName("[email protected]");
        entity.setPassword("*****");
        entity.setSubject("任务调度报警邮件");
        entity.setText("任务调度失败了,请知晓!");
        entity.setFrom("[email protected]");
        entity.setTo("[email protected]");
        SendMail(entity);
    }
}

猜你喜欢

转载自blog.csdn.net/chengkui1990/article/details/81744272