java合成文字到图片上,定时发送员工生日邮件

该代码示例展示了一个Employee类用于存储员工信息,包括生日和邮箱。在Test类中,程序读取背景图片,生成带有特定字体和样式的生日祝福文本图片,然后使用SMTP协议通过邮件服务发送给当月生日的员工,附带个性化生日祝福。
摘要由CSDN通过智能技术生成

1、Employee用户类


public class Employee {
    public int id; //员工id
    public String staffName; //员工姓名
    public String brithDate; //员工生日xxxx-mm-dd
    public String staffEmail;//员工邮箱



    public Employee() {

    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStaffName() {
        return staffName;
    }

    public void setStaffName(String staffName) {
        this.staffName = staffName;
    }

    public String getBrithDate(String birthday) {
        return brithDate;
    }

    public void setBrithDate(String brithDate) {
        this.brithDate = brithDate;
    }

    public String getStaffEmail() {
        return staffEmail;
    }

    public void setStaffEmail(String staffEmail) {
        this.staffEmail = staffEmail;
    }

    @Override
    public String toString() {
        return "staff{" +
                "id=" + id +
                ", staffName='" + staffName + '\'' +
                ", brithDate='" + brithDate + '\'' +
                ", staffEmail='" + staffEmail + '\'' +
                '}';
    



2、test类`

import sun.java2d.pipe.DrawImage;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
import javax.mail.*;
import javax.mail.internet.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Test {
    public static void createImage(String str, Font font, File outFile, File bgImageFile) throws Exception {
        // 读取背景图
        Image bgImage = ImageIO.read(bgImageFile);
        Integer width = bgImage.getWidth(null);
        Integer height = bgImage.getHeight(null);
        // 创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.drawImage(bgImage, 0, 0, width, height,null);
        g.setColor(Color.black);
        g.setFont(font);
        DrawImage drawText = new DrawImage();

        //更改
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(str.getBytes("UTF-8")), "UTF-8"));
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        boolean fontExists = Arrays.asList(ge.getAvailableFontFamilyNames()).contains("SimHei");
        if (!fontExists) {
            System.out.println("字体未正确加载");
        }

        //BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(str.getBytes()), Charset.forName("utf8")));
        String line;
        int locY = g.getFontMetrics().getHeight();
        while (null != (line = br.readLine())) {
            locY = drawStringWithFontStyleLineFeed(g, line, 0, locY, font, width - g.getFontMetrics().charWidth(' '));
            locY += g.getFontMetrics().getHeight();
        }

        g.dispose();
        // 输出png图片
        ImageIO.write(image, "png", outFile);
    }



    public static int drawStringWithFontStyleLineFeed(Graphics g, String strContent, int locX, int locY, Font font, int rowWidth){
        //获取字符串 字符的总宽度
        int strWidth = getStringLength(g, strContent);
        System.out.println("每行字符宽度:" + rowWidth);
        //获取字符高度
        int strHeight = getStringHeight(g);
        //字符串总个数
        System.out.println("字符串总个数:" + strContent.length());
        if (strWidth > rowWidth) {
            //每行的字符数
            int rowstrnum = getRowStrNum(strContent.length(), rowWidth, strWidth);
            int rows = getRows(strWidth, rowWidth);
            String temp = "";
            for (int i = 0; i < rows; i++) {
                //获取各行的String
                if (i == rows - 1) {
                    //最后一行
                    temp = strContent.substring(i * rowstrnum);
                } else {
                    temp = strContent.substring(i * rowstrnum, i * rowstrnum + rowstrnum);
                }
                if (i > 0) {
                    //第一行不需要增加字符高度,以后的每一行在换行的时候都需要增加字符高度
                    locY = locY + strHeight;
                }
                g.drawString(temp, locX, locY);
            }
        } else {
            //直接绘制
            g.drawString(strContent, locX, locY);
        }

        return locY;
    }

    private static int getRows(int strWidth, int rowWidth){
        int rows = 0;
        if (strWidth % rowWidth > 0) {
            rows = strWidth / rowWidth + 1;
        } else {
            rows = strWidth / rowWidth;
        }
        System.out.println("行数:" + rows);
        return rows;
    }

    private static int  getStringHeight(Graphics g) {
        int height = g.getFontMetrics().getHeight();
        System.out.println("字符高度:"+height);
        return height;
    }

    private static int getRowStrNum(int strnum, int rowWidth, int strWidth){
        int rowstrnum = 0;
        rowstrnum = (rowWidth * strnum) / strWidth;
        System.out.println("每行的字符数:" + rowstrnum);
        return rowstrnum;
    }

    private static int  getStringLength(Graphics g, String str) {
        int strWidth = g.getFontMetrics().stringWidth(str);
        System.out.println("字符总宽度:"+strWidth);
        return strWidth;
    }


    public static  void main(String[] args) throws MessagingException, UnsupportedEncodingException {
        Properties props = new Properties();//创建一个配置文件保存并读取信息
        props.setProperty("mail.transport.protocol", "SMTP");//SMTP邮件发送协议,POP3接收邮件协议,IMAP交互式邮件存取协议
        props.setProperty("mail.host", "smtp.exmail.qq.com");//邮件发送服务器的地址 https://service.rtxmail.net/faq/119.html
        props.setProperty("mail.smtp.auth", "true");//指定验证为true
        String subject = "祝您生日快乐~";
        //获取当日日期
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        Employee be1= new Employee();
        Employee be2= new Employee();
        Employee be3= new Employee();
        List<Employee> userlist= new ArrayList<Employee>();

        be1.setBrithDate("03-02");
        be1.setStaffEmail("fengxi@cqt.com");
        be1.setStaffName("冯怡");
//        be2.setBrithDate("02-23");
//        be2.setStaffEmail("wuhao@cqcyit.com");
//        be2.setStaffName("吴浩");
        be3.setBrithDate("03-02");
        be3.setStaffEmail("wu余@cq.com");
        be3.setStaffName("吴余");
        userlist.add(be1);
       // userlist.add(be2);
        userlist.add(be3);
        System.out.println(userlist);
        for(Employee users : userlist) {
            String emailMsg = "\n\n\n\n\n\n\n\n\n\n\n\n\n     Dear " + users.getStaffName() + ":\n\n" + "         祝你生日快乐~\n         在这个特别的日子里,感谢你 携手并进。新的一年意味着\n     更多探索的可能性,也意味着更多\n     的责任与担当。衷心祝愿你,每一\n     天都有进步,每一阶段都更精彩。\n\n" +
                    "                 集团\n" + "                 " +
                    year + "年" + month + "月" + day + "日";
            //合成图片代码
            //ImageUtil img = new ImageUtil();
            try {
                // 字体文件路径
                String fontFilePath = "D:\\code_test\\ecology\\ecology\\pubaction\\src\\main\\com\\api\\pubaction\\brithdaytest\\util\\simhei.ttf";
                // 加载字体文件
                Font font = Font.createFont(Font.TRUETYPE_FONT, new File(fontFilePath));
                // 设置字体大小和样式
                font = font.deriveFont(Font.PLAIN, 32);
                //img.createImage(emailMsg, new Font("黑体", Font.PLAIN, 32), new File("C:\\Users\\22471\\Desktop\\" + users.staffName + "happy birthday.png"), new File("C:\\Users\\22471\\Desktop\\TUPIAN.png"));
               createImage(emailMsg, font, new File("C:\\Users\\22471\\Desktop\\" + users.staffName + "happy birthday.png"), new File("C:\\Users\\22471\\Desktop\\TUPIAN.png"));
                //createImage(emailMsg, new Font("黑体", Font.PLAIN, 32), new File("C:\\Users\\22471\\Desktop\\" + users.staffName + "happy birthday.png"), new File("C:\\Users\\22471\\Desktop\\TUPIAN.png"));
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("ok");
            //        //ssl安全协议
//        MailSSLSocketFactory sf = null;
//        try {
//            sf = new MailSSLSocketFactory();
//            sf.setTrustAllHosts(true);
//        } catch (GeneralSecurityException e1) {
//            e1.printStackTrace();
//        }
//        props.put("mail.smtp.ssl.enable", "true");
//        props.put("mail.smtp.ssl.socketFactory", sf);
            //创建验证器
            Authenticator auth = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //发件人的用户名和授权码
                    return new PasswordAuthentication("wuhan", "gfwh9vQq776865H2sKh9rS");
                }
            };
            //根据配置创建会话对象, 用于和邮件服务器交互
            Session session = Session.getInstance(props, auth);


            // 2.[创建一封邮件]创建一个Message,它相当于是邮件内容
            Message message = new MimeMessage(session);//创建邮件对象
            message.setFrom(new InternetAddress("wuhan@cqit.com")); //设置发送者的邮箱地址
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(users.staffEmail)); //设置发送方式与接收者
            message.setSubject(subject);//邮件主题
            //message.setContent(emailMsg,"text/html;charset=UTF-8");

            //创建文本节点
            MimeBodyPart text = new MimeBodyPart();
            text.setContent("祝你生日快乐!<br/><img src='cid:image_flower'/>", "text/html;charset=UTF-8");


            //创建图片节点
            MimeBodyPart image = new MimeBodyPart();//新建一个存放信件内容的MimeBodyPart对象
            image.setContent(emailMsg, "text/html;charset=utf-8");//给MimeBodyPart对象设置内容和格式/编码方式
            image.setFileName(MimeUtility.encodeText("happy birthday to you.png"));
            image.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\22471\\Desktop\\" + users.staffName + "happy birthday.png")));
            //image.setDataHandler(dataHandler1);
            image.setContentID("image_flower");
            //新建一个MimeMultipart对象mm
            MimeMultipart mm = new MimeMultipart();
            //将文本、图片添加到 MimeMultipart
            mm.addBodyPart(text);
            mm.addBodyPart(image);
            //混合关系
            mm.setSubType("related");

            message.setContent(mm);//设置整个邮件的关系,将最终的混合节点mm作为邮件的内容添加到邮件对象
            message.saveChanges();//保存上面的所有设置

            // 3.[发送邮件]创建,Transport用于将邮件发送
            Transport transport = session.getTransport("smtp");

            session.setDebug(true);
            transport.connect("smtp.exmail.qq.com", "wuhan@cqit.com", "UHvysHDvExvUxthK");
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("sendMail-----结束了");
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值