Java SMTP协议发送邮件

35 篇文章 2 订阅

1、Pom依赖引用

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

2、配置文件配置邮箱基本信息

smtp_email_service.url=xx.xx.xx.xx
smtp_email_service.userName=xx@xx.com
smtp_email_service.password=密码

3、邮件工具类

//邮件实体,自定义
import xxx.PropertyConstants;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

public class MailUtils {

    public static void sendMail(MailInfo mailInfo) throws Exception{
        String host = PropertyConstants.getPropertiesKey("smtp_email_service.url");
        String userName = PropertyConstants.getPropertiesKey("smtp_email_service.userName");
        String password = PropertyConstants.getPropertiesKey("smtp_email_service.password");

        //1、连接邮件服务器的参数配置
        Properties prop = new Properties();
        //协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //服务器
        prop.setProperty("mail.smtp.host", host);
        //端口
        prop.setProperty("mail.smtp.port", "25");
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(prop,new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

  
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            //发件人
            mimeMessage.setFrom(new InternetAddress(userName));        //可以设置发件人的别名
            //收件人
            for (String to:mailInfo.getToList()){
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            }
            //抄送人
            for (String to:mailInfo.getCcList()){
                mimeMessage.addRecipient(MimeMessage.RecipientType.CC, new InternetAddress(to));
            }
            //主题
            mimeMessage.setSubject(mailInfo.getSubject(),"UTF-8");
            //时间
            mimeMessage.setSentDate(new Date());
            //容器类,可以包含多个MimeBodyPart对象
            Multipart mp = new MimeMultipart();

            //MimeBodyPart可以包装文本,图片,附件
            MimeBodyPart body = new MimeBodyPart();

            //HTML正文
            body.setContent(mailInfo.getBody(), "text/html; charset=UTF-8");
            mp.addBodyPart(body);

            //设置邮件内容
            mimeMessage.setContent(mp);

            //仅仅发送文本
            //mimeMessage.setText(content);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

4、邮件实体

import lombok.Data;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import java.util.ArrayList;
import java.util.List;

@Data
public class MailInfo {
    private String subject;
    String body;
    BodyType bodyType;
    /**
     *  收件人
     */
    List<String> toList;

    /**
     *  抄送人
     */
    List<String> ccList;

    /**
     * 附件
     */
    List<MailAttachement> attachements;

    public MailInfo(){
        this.toList=new ArrayList<>();
        this.ccList=new ArrayList<>();
        this.attachements=new ArrayList<>();
        this.bodyType=BodyType.Text;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public BodyType getBodyType() {
        return bodyType;
    }

    public void setBodyType(BodyType bodyType) {
        this.bodyType = bodyType;
    }

    public List<String> getToList() {
        return toList;
    }

    public void setToList(List<String> toList) {
        this.toList = toList;
    }

    public List<String> getCcList() {
        return ccList;
    }

    public void setCcList(List<String> ccList) {
        this.ccList = ccList;
    }

    public List<MailAttachement> getAttachements() {
        return attachements;
    }

    public void setAttachements(List<MailAttachement> attachements) {
        this.attachements = attachements;
    }
}

5、附件实体

public class MailAttachement {

    String name;
    byte[] contentStream;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getContentStream() {
        return contentStream;
    }

    public void setContentStream(byte[] contentStream) {
        this.contentStream = contentStream;
    }
}

6、方法使用实例

//设置正文
StringBuffer theMessage = new StringBuffer();
//设置具体正文内容
theMessage.append("<span style='width:100%;display:inline-block;text-align:center; font-family:宋体; font-size:29px; font-weight:bold'>xxxxxx</span>");
theMessage.append("<br>");
theMessage.append("<br>");

MailInfo mailInfo = new MailInfo();
//设置主题,title 为 String 类型
mailInfo.setSubject(title);
mailInfo.setBody(theMessage.toString());
//设置发送人,list为String集合
mailInfo.setToList(list);
//设置抄送人
mailInfo.setCcList(list);
//调用工具类
MailUtils.sendMail(mailInfo);
  • 23
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中可以使用JavaMail API来发送邮件,其中SMTP协议是最常用的邮件发送协议之一。下面是一个简单的示例代码: ```java import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SMTPJava { public static void main(String[] args) { final String username = "[email protected]"; final String password = "your_password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.example.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Testing SMTP Java"); message.setText("Hello, this is a test email from SMTP Java"); Transport.send(message); System.out.println("Mail sent successfully"); } catch (MessagingException e) { throw new RuntimeException(e); } } } ``` 其中,需要修改的参数包括: - `username`和`password`:你的邮箱账号和密码; - `props.put("mail.smtp.host", "smtp.example.com");`:将`smtp.example.com`替换为你的邮箱提供商的SMTP服务器地址; - `message.setFrom(new InternetAddress("[email protected]"));`和`InternetAddress.parse("[email protected]")`:将`[email protected]`和`[email protected]`替换为你的发件人和收件人的邮箱地址。 需要注意的是,有些邮箱提供商可能需要设置授权码(例如Gmail),可以在邮箱设置中找到授权码,并将其替换为密码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻猴儿

小编,多谢客官留下的赏钱。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值