我测试用的QQ,需要到QQ邮箱里开通pop3服务
import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; public class SendMail { private static final String MAIL_CC = "xxx@qq.com";// 邮件的抄送人 private static final String MAIL_BCC = "xxx@qq.com";// 邮件的密送人 // 设置邮件服务器 private static final String send_email_host_name = "smtp.qq.com"; // 设置安全连接端口号 private static final String send_email_ssl_port = "465"; // 发送Email用户名 private static final String send_email_user_name = "xxx@qq.com"; // 发送Email密码。即上面开通的pop3的授权码 private static final String send_email_user_pwd = "xxx"; // 发送Email编码 private static final String send_email_charset = "UTF-8"; public static void main(String[] args) throws Exception { sendPlainEmail(send_email_user_name, "这是一个subject", "this is content"); } /** * @todo 发送纯文本的Email * @param receiver 收信人 * @param subjecct Email主题 * @param msg Email内容 * @throws EmailException * @date 2019年7月31日 * @author yanan */ public static void sendPlainEmail(String receiver, String subjecct, String msg) throws EmailException { SimpleEmail email = new SimpleEmail(); email.setHostName(send_email_host_name); email.setSSLOnConnect(true);// 设置使用安全连接 email.setSslSmtpPort(send_email_ssl_port); email.setAuthentication(send_email_user_name, send_email_user_pwd); try { email.addTo(receiver, "receiver");//评论区有猿讨论群发接口,其实直接在这里多次addTo增加收信人就行了 email.setCharset(send_email_charset); email.setFrom(send_email_user_name); email.addBcc(MAIL_BCC); email.addCc(MAIL_CC); email.setSubject(subjecct); email.setMsg(msg); email.send(); } catch (EmailException e) { throw new EmailException(e); } } }
20191118:今天发送126,发现126邮箱不需要安全链接,即做如下更改即可
email.setSSLOnConnect(false);// 设置不使用安全连接 //email.setSslSmtpPort(send_email_ssl_port);
126的send_email_host_name=smtp.126.com
20191120:今日发现126邮箱发送邮件后可以自动保存到已发送,但QQ不行,程序实现如下:@参考文章3,@参考文章4
email.send后添加:
saveEmailToSentMailFolder(email.getMimeMessage());
/** * 获取用户的发件箱文件夹 * * @param message * 信息 * @param store * 存储 * @return * @throws IOException * @throws MessagingException */ private static Folder getSentMailFolder(Message message, Store store) throws IOException, MessagingException { // 准备连接服务器的会话信息 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", ConfigUtil.getProperty("mail.imap.host")); props.setProperty("mail.imap.port", ConfigUtil.getProperty("mail.imap.port")); /** QQ邮箱需要建立ssl连接 */ props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.starttls.enable", "true"); props.setProperty("mail.imap.socketFactory.port", ConfigUtil.getProperty("mail.imap.port")); // 创建Session实例对象 Session session = Session.getInstance(props); URLName urln = new URLName("imap", ConfigUtil.getProperty("mail.imap.host"), Integer.parseInt(ConfigUtil.getProperty("mail.imap.port")), null, ConfigUtil.getProperty("sendemail_username"), ConfigUtil.getProperty("sendemail_userpwd")); // 创建IMAP协议的Store对象 store = session.getStore(urln); store.connect(); // 获得发件箱 Folder folder = store.getFolder("Sent Messages"); // 以读写模式打开发件箱 folder.open(Folder.READ_WRITE); return folder; } /** * 保存邮件到发件箱 * * @param message * 邮件信息 */ private static void saveEmailToSentMailFolder(Message message) { Store store = null; Folder sentFolder = null; try { sentFolder = getSentMailFolder(message, store); message.setFlag(Flag.SEEN, true); // 设置已读标志 sentFolder.appendMessages(new Message[] { message }); System.out.println("已保存到发件箱..."); } catch (Exception e) { e.printStackTrace(); } finally { // 判断发件文件夹是否打开如果打开则将其关闭 if (sentFolder != null && sentFolder.isOpen()) { try { sentFolder.close(true); } catch (MessagingException e) { e.printStackTrace(); } } // 判断邮箱存储是否打开如果打开则将其关闭 if (store != null && store.isConnected()) { try { store.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }
完整代码如下:
package yanan.util; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.mail.Flags.Flag; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.URLName; import org.apache.commons.io.FilenameUtils; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.MultiPartEmail; import org.apache.commons.mail.SimpleEmail; import sun.misc.BASE64Encoder; public class SendMail { // 发送Email编码 private static final String send_email_charset = "UTF-8"; public static void main(String[] args) throws Exception { sendPlainEmail("xxx@qq.com", "ceshi", "this is content"); //Map<String, String> multipart=new HashMap<String,String>(); //sendMultipartEmail("xxx@qq.com", multipart,"体检报告2019" , "您的体检报告"); } /** * @todo 发送纯文本的Email * @param receiver 收信人 * @param subjecct Email主题 * @param content Email内容 * @throws EmailException * @date 2019年7月31日 * @author yanan */ public static boolean sendPlainEmail(String receiver, String subjecct, String content){ System.out.println("发送邮件开始"); SimpleEmail email = new SimpleEmail(); email.setHostName(ConfigUtil.getProperty("sendemail_hostname")); email.setSSLOnConnect(false);// 设置使用安全连接 if(ConfigUtil.getProperty("sendemail_sslport")!=null&&ConfigUtil.getProperty("sendemail_sslport").equals("T")){ email.setSslSmtpPort(ConfigUtil.getProperty("sendemail_sslport")); } email.setAuthentication(ConfigUtil.getProperty("sendemail_username"), ConfigUtil.getProperty("sendemail_userpwd")); try { email.addTo(receiver, "receiver");//评论区有猿讨论群发接口,其实直接在这里多次addTo增加收信人就行了 email.setCharset(send_email_charset); email.setFrom(ConfigUtil.getProperty("sendemail_username")); if(ConfigUtil.getProperty("sendemail_misong")!=null&&!ConfigUtil.getProperty("sendemail_misong").equals("")){ email.addBcc(ConfigUtil.getProperty("sendemail_misong")); } if(ConfigUtil.getProperty("sendemail_chaosong")!=null&&!ConfigUtil.getProperty("sendemail_chaosong").equals("")){ email.addCc(ConfigUtil.getProperty("sendemail_chaosong")); } email.setSubject(subjecct); email.setMsg(content); email.send(); saveEmailToSentMailFolder(email.getMimeMessage()); return true; } catch (EmailException e) { e.printStackTrace(); return false; } } /** * 获取用户的发件箱文件夹 * * @param message * 信息 * @param store * 存储 * @return * @throws IOException * @throws MessagingException */ private static Folder getSentMailFolder(Message message, Store store) throws IOException, MessagingException { // 准备连接服务器的会话信息 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", ConfigUtil.getProperty("mail.imap.host")); props.setProperty("mail.imap.port", ConfigUtil.getProperty("mail.imap.port")); /** QQ邮箱需要建立ssl连接 */ props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.starttls.enable", "true"); props.setProperty("mail.imap.socketFactory.port", ConfigUtil.getProperty("mail.imap.port")); // 创建Session实例对象 Session session = Session.getInstance(props); URLName urln = new URLName("imap", ConfigUtil.getProperty("mail.imap.host"), Integer.parseInt(ConfigUtil.getProperty("mail.imap.port")), null, ConfigUtil.getProperty("sendemail_username"), ConfigUtil.getProperty("sendemail_userpwd")); // 创建IMAP协议的Store对象 store = session.getStore(urln); store.connect(); // 获得发件箱 Folder folder = store.getFolder("Sent Messages"); // 以读写模式打开发件箱 folder.open(Folder.READ_WRITE); return folder; } /** * 保存邮件到发件箱 * * @param message * 邮件信息 */ private static void saveEmailToSentMailFolder(Message message) { Store store = null; Folder sentFolder = null; try { sentFolder = getSentMailFolder(message, store); message.setFlag(Flag.SEEN, true); // 设置已读标志 sentFolder.appendMessages(new Message[] { message }); System.out.println("已保存到发件箱..."); } catch (Exception e) { e.printStackTrace(); } finally { // 判断发件文件夹是否打开如果打开则将其关闭 if (sentFolder != null && sentFolder.isOpen()) { try { sentFolder.close(true); } catch (MessagingException e) { e.printStackTrace(); } } // 判断邮箱存储是否打开如果打开则将其关闭 if (store != null && store.isConnected()) { try { store.close(); } catch (MessagingException e) { e.printStackTrace(); } } } } /** * 发送多个带附件的Email * @param receiver 收信人 * @param multipart 附件map key:附件名字不需加文件扩展名,map value:附件路径和名字,如果为网络资源,请以http开头 * @param subjecct Email主题 * @param msg Email内容 * @throws EmailException */ @SuppressWarnings({ "deprecation" }) public static void sendMultipartEmail(String receiver,Map<String, String> multipart,String subjecct,String msg) throws EmailException{ MultiPartEmail email = new MultiPartEmail(); email.setHostName(ConfigUtil.getProperty("sendemail_hostname")); boolean is_ssl = true; email.setSSL(is_ssl); email.setSslSmtpPort(ConfigUtil.getProperty("sendemail_sslport")); email.setAuthentication(ConfigUtil.getProperty("sendemail_username"), ConfigUtil.getProperty("sendemail_userpwd")); Iterator<Entry<String,String>> iter = multipart.entrySet().iterator(); String encoding = System.getProperty("file.encoding"); BASE64Encoder encoder = new BASE64Encoder(); while (iter.hasNext()) { Map.Entry<java.lang.String, java.lang.String> entry = (Map.Entry<java.lang.String, java.lang.String>) iter .next(); String multiPath = entry.getValue(); String multiName = entry.getKey() +"." + FilenameUtils.getExtension(multiPath); if(multiName!=null && multiPath!=null){ EmailAttachment attachment = new EmailAttachment(); if(multiPath.startsWith("http:")){ try { attachment.setURL(new URL(multiPath)); } catch (MalformedURLException e) { throw new EmailException(e); } }else{ attachment.setPath(multiPath); } attachment.setName("=?"+encoding+"?B?"+encoder.encode(multiName.getBytes())+"?="); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription(""); email.attach(attachment); } } if(receiver!=null){ try { email.addTo(receiver,"receiver"); email.setCharset(send_email_charset); email.setFrom(ConfigUtil.getProperty("sendemail_username")); email.setSubject(subjecct); email.setMsg(msg); email.send(); } catch (EmailException e) { throw new EmailException(e); } } } }
为了广大网友拿来即用,将配置文件相关参数也一并贴出
#邮件服务器配置 # 邮件的抄送人 sendemail_chaosong= #邮件的密送人 sendemail_misong= #设置邮件服务器smtp.qq.comsmtp.126.com sendemail_hostname=smtp.qq.com #设置是否需要安全链接,T是F否.126邮箱不需要,qq需要 sendemail_sslneed=T #设置安全连接端口号QQ465 sendemail_sslport= #发送Email用户名 sendemail_username=xxx@qq.com #发送Email密码。即上面开通的pop3的授权码 sendemail_userpwd=xxxxx # IMAP服务器imap.126.com 143 imap.qq.com 993 mail.imap.host=imap.qq.com mail.imap.port=993