java实现邮件发送
//创建一个配置文件并保存 Properties properties = new Properties(); properties.setProperty("mail.host","smtp.qq.com"); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); //QQ存在一个特性设置SSL加密 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() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("503043053@qq.com","xqalcxlrurfbbgdg"); } }); //开启debug模式 session.setDebug(true); //获取连接对象 Transport transport = session.getTransport(); //连接服务器 transport.connect("smtp.qq.com","503043053@qq.com","xqalcxlrurfbbgdg"); //创建邮件对象 MimeMessage mimeMessage = new MimeMessage(session); //邮件发送人 mimeMessage.setFrom(new InternetAddress("503043053@qq.com")); //邮件接收人 mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("a8886762@gmail.com")); //#region 简单内容 // //邮件标题 // mimeMessage.setSubject("Hello Mail"); // // //邮件内容 // mimeMessage.setContent("我的想法是把代码放进一个循环里","text/html;charset=UTF-8"); //#endregion //邮件内容 //准备图片数据 MimeBodyPart image = new MimeBodyPart(); DataHandler handler = new DataHandler(new FileDataSource("D:\\4_STUDY\\JAVA\\mavenmodule02\\test01\\src\\main\\java\\com\\doubleh\\email\\java学习路线图.jpg")); image.setDataHandler(handler); image.setContentID("test.png"); //设置图片id //准备文本 MimeBodyPart text = new MimeBodyPart(); text.setContent("这是一段文本<img src='cid:test.png'>","text/html;charset=utf-8"); //附件 MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler(new DataHandler(new FileDataSource("D:\\4_STUDY\\JAVA\\mavenmodule02\\test01\\src\\main\\java\\com\\doubleh\\email\\新建 DOC 文档.doc"))); appendix.setFileName("test.doc"); //拼装邮件正文 MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(image); mimeMultipart.addBodyPart(text); mimeMultipart.setSubType("related");//文本和图片内嵌成功 //将拼装好的正文内容设置为主体 MimeBodyPart contentText = new MimeBodyPart(); contentText.setContent(mimeMultipart); //拼接附件 MimeMultipart allFile = new MimeMultipart(); allFile.addBodyPart(appendix);//附件 allFile.addBodyPart(contentText);//正文 allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed //放到Message消息中 mimeMessage.setContent(allFile); mimeMessage.saveChanges();//保存修改 //发送邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //关闭连接 transport.close();