• java发送邮件


    java发送普通文本邮件

    导入需要的jar包

    发送邮件需要的jar有2个:activation.jar和mail.jar

    java.sun.com官方网站去搜,下载javamail和JAF两个包,只要取其中的mail.jar和activaction.jar即可。

    我这里已经打包了,可以直接下载:邮件发送jar包

    创建properties配置文件

    创建properties文件存放邮箱服务器和卡密等信息,如果不单独以配置文件的形式存在,直接在java程序中设置也是可以的,但是不利于封装。

    #----------------这两个是构建session必须的字段----------
    #smtp服务器		smtp.qq.com 是qq邮箱
    mail.smtp.host=smtp.163.com
    
    #身份验证:是
    mail.smtp.auth=true
    #--------------------------------------------------------------
    
    #发送者的邮箱用户名
    mail.sender.username=xxx@xx.com
    #发送者的邮箱密码
    mail.sender.password=xxx
    

    java代码

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeUtility;
    
    public class SimpleTextMail {
    	/**
    	 * Message对象将存储我们实际发送的电子邮件信息,
    	 * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。
    	 */
    	private MimeMessage message;
    
    	/**
    	 * Session类代表JavaMail中的一个邮件会话。 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。
    	 * 
    	 * JavaMail需要Properties来创建一个session对象。 寻找"mail.smtp.host" 属性值就是发送邮件的主机
    	 * 寻找"mail.smtp.auth" 身份验证,目前免费邮件服务器都需要这一项
    	 */
    	private Session session;
    
    	/***
    	 * 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。 Transport
    	 * 是用来发送信息的,而Store用来收信。对于这的教程我们只需要用到Transport对象。
    	 */
    	private Transport transport;
    
    	private String mailHost = "";
    	private String sender_username = "";
    	private String sender_password = "";
    
    	private Properties properties = new Properties();
    
    	/*
    	 * 初始化方法:对本对象中的参数用配置文件进行初始化参数设置
    	 */
    	public SimpleTextMail(boolean debug) {
    		// 输入流关联properties配置文件:设置properties文件路径
    		InputStream in = SimpleTextMail.class.getResourceAsStream("/mail.properties");
    		try {
    			// 加载配置(反序列化)
    			properties.load(in);
    			// 根据键加载值
    			this.mailHost = properties.getProperty("mail.smtp.host");
    			this.sender_username = properties.getProperty("mail.sender.username");
    			this.sender_password = properties.getProperty("mail.sender.password");
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		session = Session.getInstance(properties);
    		session.setDebug(debug); // 开启后有调试信息
    		message = new MimeMessage(session);
    	}
    
    	/**
    	 * 发送邮件
    	 * 
    	 * @param subject
    	 *            邮件主题
    	 * @param sendHtml
    	 *            邮件内容
    	 * @param receiveUser
    	 *            收件人地址
    	 */
    	public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser) {
    		try {
    			// 发件人
    			// InternetAddress from = new InternetAddress(sender_username);
    			// 下面这个是设置发送人的Nick name
    			InternetAddress from = new InternetAddress(MimeUtility.encodeWord("Boss系统") + " <" + sender_username + ">");
    			message.setFrom(from);
    
    			// 收件人
    			InternetAddress to = new InternetAddress(receiveUser);
    			message.setRecipient(Message.RecipientType.TO, to);		// 还可以有CC、BCC
    
    			// 邮件主题
    			message.setSubject(subject);
    
    			String content = sendHtml.toString();
    			// 邮件内容,也可以使纯文本"text/plain"
    			message.setContent(content, "text/html;charset=UTF-8");
    
    			// 保存邮件
    			message.saveChanges();
    
    			transport = session.getTransport("smtp");
    			// smtp验证,就是你用来发邮件的邮箱用户名密码
    			transport.connect(mailHost, sender_username, sender_password);
    			// 发送
    			transport.sendMessage(message, message.getAllRecipients());
    			// System.out.println("send success!");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (transport != null) {
    				try {
    					transport.close();
    				} catch (MessagingException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    
    	/**
    	 * 主方法调用上面的方法以发送邮件
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		SimpleTextMail se = new SimpleTextMail(false);
    		se.doSendHtmlEmail("邮件主题", "邮件内容", "yansl1484@163.com");
    	}
    }
    

    大致地解读一下上面的程序

    1. SimpleTextMail对象(本类)被创建时,会用如下构造方法进行初始化
    public SimpleTextMail(boolean debug) {
           //...................
        }
    

    首先,读取配置文件并反序列化获得其设置的参数给类中已经定义好的对应属性mailHost、账户、密码赋值,同时给类中的session和message等对象赋值。

    1. 定义发送邮件的方法,根据用户传入的内容和目标邮箱地址发送邮件。

    我们可以把这个类封装起来,把构造私有,变成一个工具类。这样可以很方便地复用。



    发送附件

    由于目前我的项目需求没有说要发送附件的,所以我没有实践,只把别的地方copy过来的教程贴过来供以后参考

    用到了multipart对象

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    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 JavaMailWithAttachment {
        private MimeMessage message;
        private Session session;
        private Transport transport;
    
        private String mailHost = "";
        private String sender_username = "";
        private String sender_password = "";
    
        private Properties properties = new Properties();
    
        /*
         * 初始化方法
         */
        public JavaMailWithAttachment(boolean debug) {
            InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");
            try {
                properties.load(in);
                this.mailHost = properties.getProperty("mail.smtp.host");
                this.sender_username = properties.getProperty("mail.sender.username");
                this.sender_password = properties.getProperty("mail.sender.password");
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            session = Session.getInstance(properties);
            session.setDebug(debug);// 开启后有调试信息
            message = new MimeMessage(session);
        }
    
        /**
         * 发送邮件
         * 
         * @param subject
         *            邮件主题
         * @param sendHtml
         *            邮件内容
         * @param receiveUser
         *            收件人地址
         * @param attachment
         *            附件
         */
        public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
            try {
                // 发件人
                InternetAddress from = new InternetAddress(sender_username);
                message.setFrom(from);
    
                // 收件人
                InternetAddress to = new InternetAddress(receiveUser);
                message.setRecipient(Message.RecipientType.TO, to);
    
                // 邮件主题
                message.setSubject(subject);
    
                // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
                Multipart multipart = new MimeMultipart();
                
                // 添加邮件正文
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
                multipart.addBodyPart(contentPart);
                
                // 添加附件的内容
                if (attachment != null) {
                    BodyPart attachmentBodyPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    
                    // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
                    // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                    //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                    //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
                    
                    //MimeUtility.encodeWord可以避免文件名乱码
                    attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                    multipart.addBodyPart(attachmentBodyPart);
                }
                
                // 将multipart对象放到message中
                message.setContent(multipart);
                // 保存邮件
                message.saveChanges();
    
                transport = session.getTransport("smtp");
                // smtp验证,就是你用来发邮件的邮箱用户名密码
                transport.connect(mailHost, sender_username, sender_password);
                // 发送
                transport.sendMessage(message, message.getAllRecipients());
    
                System.out.println("send success!");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (transport != null) {
                    try {
                        transport.close();
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            JavaMailWithAttachment se = new JavaMailWithAttachment(true);
            File affix = new File("c:\测试-test.txt");
            se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);//
        }
    }
    
  • 相关阅读:
    mysql子查询
    hibernate lazy属性true false extra 抓取策略
    unittest下,生成的测试报告
    python创建excel文件,并进行读与存操作
    configparser模块简介
    PyCharm里面的c、m、F、f、v、p分别代表什么含义?
    Python之路(第十七篇)logging模块
    configparser模块简介
    python中os.sep的作用以及sys._getframe().f_back.f_code.co_xxx的含义
    os.getcwd()和os.path.realpath(__file__)的区别
  • 原文地址:https://www.cnblogs.com/iisme/p/10480254.html
Copyright © 2020-2023  润新知