java 发送邮件 带附件或者表格

4 篇文章 0 订阅
package com.sub.utils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.List;
import java.util.Properties;

public class MailUtil implements Runnable {
    private String email;// 收件人邮箱
    private String content;//内容
    private String filename;//附件
    private String subject;//主题
    private Boolean ishtml;//是否为html代码

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getSubject() {
        return subject;
    }

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

    public Boolean getIshtml() {
        return ishtml;
    }

    public void setIshtml(Boolean ishtml) {
        this.ishtml = ishtml;
    }

    public MailUtil(Builder builder) {
        this.content = builder.content;
        this.filename = builder.filename;
        this.subject = builder.subject;
        this.email = builder.email;
        this.ishtml = builder.ishtml;
    }

    public static class Builder{
        private String email;// 收件人邮箱
        private String content="";//内容
        private String filename=null;//附件
        private String subject="这是邮件";//主题
        private Boolean ishtml = false;//是否为html代码

        public Builder setContent(String content_b){
            this.content = content_b;
            return this;
        }
        public Builder setFilename(String filename_b){
            this.filename = filename_b;
            return this;
        }
        public Builder setSubject(String subject_b){
            this.subject = subject_b;
            return this;
        }
        public Builder isHtml(){
            this.ishtml = true;
            return this;
        }

        public MailUtil buildWithEmail(String email_b) {
            this.email = email_b;
            return new MailUtil(this);
        }
    }



    public void run() {

        String from = "******";// 发件人电子邮箱
        String host = "smtp.ym.163.com"; // 指定发送邮件的主机
        Properties properties = System.getProperties();// 获取系统属性
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证
 
        try {
            //QQ邮箱需要下面这段代码,163邮箱不需要
//            MailSSLSocketFactory sf = new MailSSLSocketFactory();
//            sf.setTrustAllHosts(true);
//            properties.put("mail.smtp.ssl.enable", "true");
//            properties.put("mail.smtp.ssl.socketFactory", sf);

            //获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("****", "****"); // 发件人邮箱账号、授权码
                }
            });
 
            // 创建邮件对象
            Message message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(from));
            // 设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 设置邮件主题
            message.setSubject(subject);
            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();
            // 消息
            if (ishtml){
                messageBodyPart.setContent(content,"text/html;charset=UTF-8");
            }else {
                messageBodyPart.setText(content);
            }
            // 创建多重消息
            Multipart multipart = new MimeMultipart();
            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);
            // 附件部分
            if (filename!=null){
                BodyPart messageAttachmentPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filename);
                messageAttachmentPart.setDataHandler(new DataHandler(source));
                messageAttachmentPart.setFileName(filename);
                multipart.addBodyPart(messageAttachmentPart);
            }
            message.setContent(multipart);
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("邮件发送失败"+subject,e);
        }
    }

    public static StringBuilder
    getTableStart(String head[],String title){

        StringBuilder table=new StringBuilder();
        table.append("    <html>");
        table.append("     <head>");
        table.append("      <title> New Document </title>");
        table.append("     </head>");
        table.append("    ");
        table.append("    <style type=\"text/css\">");
        table.append("    table { ");
        table.append("      margin: 10px 0 30px 0;");
        table.append("      font-size: 13px;");
        table.append("    }");
        table.append("    ");
        table.append("    table caption { ");
        table.append("      text-align:left;");
        table.append("    }");
        table.append("    ");
        table.append("    table tr th { ");
        table.append("      background: #3B3B3B;");
        table.append("      color: #FFF;");
        table.append("      padding: 7px 4px;");
        table.append("      text-align: left;");
        table.append("    }");
        table.append("    ");
        table.append("    table tr td { ");
        table.append("      color: #FFF;");
        table.append("      padding: 7px 4px;");
        table.append("      text-align: left;");
        table.append("    }");
        table.append("    ");
        table.append("    table tr.odd{");
        table.append("        background-color:#cef;");
        table.append("    }");
        table.append("    ");
        table.append("    table tr.even{");
        table.append("        background-color:#ffc;");
        table.append("    }");
        table.append("      ");
        table.append("    table tr td { ");
        table.append("      color: #47433F;");
        table.append("      border-top: 1px solid #FFF;");
        table.append("    }");
        table.append("     </style>");
        table.append("    ");
        table.append("     <body>");
        table.append("<h2>"+title+"<h2/>");
        table.append("    <table style=\"width:500px; border-spacing:0;\">  ");
        table.append("       <tr>  ");
        for (int i=0;i<head.length;i++){
            table.append("          <th>"+head[i]+"</th>  ");
        }
        table.append("       </tr>  ");
        return table;
    }
    public static StringBuilder getTableEnd(StringBuilder table) {
        table.append("    </table> ");
        table.append("     </body>");
        table.append("    </html>");
        return table;
    }
}

测试

package com.sub.utils;

import com.sub.model.Employee;

import java.util.ArrayList;
import java.util.List;

public class Test {

	@org.junit.Test
	public void start(){

		String head[] = {"账号","密码"};
		List<Employee> employees = new ArrayList<Employee>(2);
		Employee employee = new Employee();
		employee.setName("小明");
		employee.setPassword("123");
		employees.add(employee);
		employee.setName("小张");
		employee.setPassword("456");
		employees.add(employee);


		StringBuilder tableStart = MailUtil.getTableStart(head,"账号密码");
		for (int i=0;i<employees.size();i++){
			String tr = "<tr class=\"odd\">";
			if (i%2==1){
				tr = "<tr class=\"even\">";
			}
			tableStart.append("     "+tr+"    ");
			tableStart.append("         <td>"+employees.get(i).getName()+"</td>  ");
			tableStart.append("         <td>"+employees.get(i).getPassword()+"</td>  ");
			tableStart.append("       </tr>  ");
		}
		StringBuilder table = MailUtil.getTableEnd(tableStart);
		MailUtil mail = new MailUtil.Builder()
				.setContent(table.toString())
				.isHtml()
        //      .setFilename("") 附件路径
				.buildWithEmail("*****");//收件人邮箱
        mail.run();
	}

}

接收到的邮件

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是 Java 发送附件邮件的示例代码: ```java import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class SendEmailWithAttachment { public static void main(String[] args) throws Exception { // 邮件配置 String host = "smtp.163.com"; // SMTP 服务器地址 int port = 25; // SMTP 服务器端口 String username = "your_email@163.com"; // 发件人邮箱账号 String password = "your_email_password"; // 发件人邮箱密码 String from = "your_email@163.com"; // 发件人邮箱地址 String to = "recipient_email@example.com"; // 收件人邮箱地址 String subject = "邮件主题"; String text = "邮件正文"; // 创建邮件会话 Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // 创建邮件消息 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); // 创建邮件正文 MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(text, "text/plain;charset=UTF-8"); // 创建邮件附件 MimeBodyPart attachmentPart = new MimeBodyPart(); String attachmentFilePath = "attachment.txt"; // 附件文件路径 attachmentPart.attachFile(attachmentFilePath); attachmentPart.setFileName(MimeUtility.encodeText(attachmentPart.getFileName())); // 创建邮件多部分内容 MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("邮件发送成功"); } } ``` 其中,需要将 `host`、`port`、`username`、`password`、`from`、`to`、`subject`、`text` 和 `attachmentFilePath` 替换为实际的值。 需要注意的是,附件文件路径需要使用绝对路径,并且需要保证附件文件存在。另外,为了避免中文文件名乱码,需要使用 `MimeUtility.encodeText()` 方法对附件文件名进行编码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值