需求:邮件发送 使用jdk源生api——java.mail实现发邮件功能
以下代码即可发送邮件,以qq邮箱为例package com.example.demo.emailinfo;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 java.io.unsupportedencodingexception;import java.util.*;public class sendemailinfo { public static void main(string[] args) throws messagingexception, unsupportedencodingexception { string smtpserver = "smtp.qq.com"; string username = "939089358@qq.com"; //这里是你开通smtp协议的授权码,若是公司自定义服务器,可无需授权码,但需要配置证书,文章后面有详解 string password = "***********"; string receiver = "939089358@qq.com"; string receiver2 = "低调ai实验室@126.com"; //这里的配置可以自己抽取成工具 properties properties = new properties(); map<string, object> map = new hashmap<>(); //常用smtp使用配置,可以在其他文章中获取:这里针对使用qq发送邮件 map.put("mail.transport.protocol","smtp"); map.put("mail.smtp.host",smtpserver); map.put("mail.smtp.auth","true"); map.put("mail.smtp.port","465"); map.put("mail.smtp.socketfactory.class","javax.net.ssl.sslsocketfactory"); map.put("mail.smtp.socketfactory.fallback",false); map.put("mail.smtp.socketfactory.port","465"); map.put("mail.smtp.starttls.enable","true"); properties.putall(map); //创建会话对象,用户邮件和服务器的交互 session session = session.getdefaultinstance(properties);// session.setdebug(true); //查看发送邮件的log //创建一邮件 mimemessage message = new mimemessage(session); internetaddress senderaddress = new internetaddress(username,"设置自定义发件人名称","utf-8"); message.setfrom(senderaddress); message.setrecipient(message.recipienttype.to,new internetaddress(receiver,"收件人自定义名称","utf-8")); message.setsubject("设置发送的主题:比如:邀请函","utf-8"); message.setcontent("内容:邀请你和我一起约会,在屋顶吹晚风,看星星,吃水果","text/html;charset=utf-8"); message.setsentdate(new date()); message.savechanges(); //用session 获取传输对象,然后连接发件人 transport transport = session.gettransport(); transport.connect(username,password); transport.sendmessage(message,message.getallrecipients()); transport.close(); system.out.println("发送成功"); }}
若要使用企业内部自搭服务器,则需要在jdk文件中配置一个授权证书,操作如下:
/* * copyright 2006 sun microsystems, inc. all rights reserved. * * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - neither the name of sun microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * this software is provided by the copyright holders and contributors "as * is" and any express or implied warranties, including, but not limited to, * the implied warranties of merchantability and fitness for a particular * purpose are disclaimed. in no event shall the copyright owner or * contributors be liable for any direct, indirect, incidental, special, * exemplary, or consequential damages (including, but not limited to, * procurement of substitute goods or services; loss of use, data, or * profits; or business interruption) however caused and on any theory of * liability, whether in contract, strict liability, or tort (including * negligence or otherwise) arising in any way out of the use of this * software, even if advised of the possibility of such damage. */ import java.io.*;import java.net.url; import java.security.*;import java.security.cert.*; import javax.net.ssl.*; public class installcert { public static void main(string[] args) throws exception { string host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { string[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : integer.parseint(c[1]); string p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.tochararray(); } else { system.out.println("usage: java installcert <host>[:port] [passphrase]"); return; } file file = new file("jssecacerts"); if (file.isfile() == false) { char sep = file.separatorchar; file dir = new file(system.getproperty("java.home") + sep + "lib" + sep + "security"); file = new file(dir, "jssecacerts"); if (file.isfile() == false) { file = new file(dir, "cacerts"); } } system.out.println("loading keystore " + file + "..."); inputstream in = new fileinputstream(file); keystore ks = keystore.getinstance(keystore.getdefaulttype()); ks.load(in, passphrase); in.close(); sslcontext context = sslcontext.getinstance("tls"); trustmanagerfactory tmf = trustmanagerfactory.getinstance(trustmanagerfactory.getdefaultalgorithm()); tmf.init(ks); x509trustmanager defaulttrustmanager = (x509trustmanager)tmf.gettrustmanagers()[0]; savingtrustmanager tm = new savingtrustmanager(defaulttrustmanager); context.init(null, new trustmanager[] {tm}, null); sslsocketfactory factory = context.getsocketfactory(); system.out.println("opening connection to " + host + ":" + port + "..."); sslsocket socket = (sslsocket)factory.createsocket(host, port); socket.setsotimeout(10000); try { system.out.println("starting ssl handshake..."); socket.starthandshake(); socket.close(); system.out.println(); system.out.println("no errors, certificate is already trusted"); } catch (sslexception e) { system.out.println(); e.printstacktrace(system.out); } x509certificate[] chain = tm.chain; if (chain == null) { system.out.println("could not obtain server certificate chain"); return; } bufferedreader reader = new bufferedreader(new inputstreamreader(system.in)); system.out.println(); system.out.println("server sent " + chain.length + " certificate(s):"); system.out.println(); messagedigest sha1 = messagedigest.getinstance("sha1"); messagedigest md5 = messagedigest.getinstance("md5"); for (int i = 0; i < chain.length; i++) { x509certificate cert = chain[i]; system.out.println (" " + (i + 1) + " subject " + cert.getsubjectdn()); system.out.println(" issuer " + cert.getissuerdn()); sha1.update(cert.getencoded()); system.out.println(" sha1 " + tohexstring(sha1.digest())); md5.update(cert.getencoded()); system.out.println(" md5 " + tohexstring(md5.digest())); system.out.println(); } system.out.println("enter certificate to add to trusted keystore or 'q' to quit: [1]"); string line = reader.readline().trim(); int k; try { k = (line.length() == 0) ? 0 : integer.parseint(line) - 1; } catch (numberformatexception e) { system.out.println("keystore not changed"); return; } x509certificate cert = chain[k]; string alias = host + "-" + (k + 1); ks.setcertificateentry(alias, cert); outputstream out = new fileoutputstream("jssecacerts"); ks.store(out, passphrase); out.close(); system.out.println(); system.out.println(cert); system.out.println(); system.out.println ("added certificate to keystore 'jssecacerts' using alias '" + alias + "'"); } private static final char[] hexdigits = "0123456789abcdef".tochararray(); private static string tohexstring(byte[] bytes) { stringbuilder sb = new stringbuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(hexdigits[b >> 4]); sb.append(hexdigits[b & 15]); sb.append(' '); } return sb.tostring(); } private static class savingtrustmanager implements x509trustmanager { private final x509trustmanager tm; private x509certificate[] chain; savingtrustmanager(x509trustmanager tm) { this.tm = tm; } public x509certificate[] getacceptedissuers() { throw new unsupportedoperationexception(); } public void checkclienttrusted(x509certificate[] chain, string authtype) throws certificateexception { throw new unsupportedoperationexception(); } public void checkservertrusted(x509certificate[] chain, string authtype) throws certificateexception { this.chain = chain; tm.checkservertrusted(chain, authtype); } } }
证书生成步骤:1、完整复制以上java代码,放到桌面上新建了一个跟类名相同的.java文件,并放入新建文件夹中
2、cmd打开命令窗口,编译:javac installcert.java文件
3、运行:java installcert java请求出错的站点url
即自行搭建的服务器域名:例如:smtp.airow.com
4、然后输入1退出。
5、检查桌面,会生成一个jssecacerts的文件,把该文件设置到你的jdk下的/jre/lib/security目录下即可
6、若要上线功能,需要运维添加并导入证书。
7、若不使用企业或个人自搭服务器发送邮件,则无需配置证书。
以上就是怎么使用java自带的mail api实现邮件发送功能的详细内容。