首先进入自己的QQ邮箱,在设置中修改账户信息

然后来至底部

点击开启,再用手机发送对应信息到指定号码,然后点击我已发送

获取授权码

注意提示:

到这里,相信你已经开通了SMTP服务,这样就可以在java code发送邮件了


接下来的是Spring 中使用邮件服务

首先是配置信息使用的是587端口,刚开始用465端口我纠结了好久(使用465端口的错误详情),用不了,你可以尝试,默认的25端口应该也是不适合的

    <!-- 邮件服务 --><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="smtp.qq.com"/><property name="port" value="587"/>//或许你可以用465端口,默认的25不适合<property name="protocol" value="smtp"/><property name="username" value="785427346@qq.com"/><property name="password" value="xxxxxxxxxxxx"/>//这里的是你通过短信后,获取的授权码<property name="defaultEncoding" value="UTF-8"/><property name="javaMailProperties">  <props>  <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.timeout">25000</prop>  </props>  </property>  </bean><!-- this is a template message that we can pre-load with default state --><bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"><property name="from" value="785427346@qq.com"/><property name="subject" value="尝试发邮件"/></bean><bean id="orderManager" class="cn.cherish.common.SimpleOrderManager"><property name="mailSender" ref="mailSender"/><property name="templateMessage" ref="templateMessage"/></bean>

用maven引入的jar包

    <!-- 邮件 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>

下面只是一个工具类作简单例子,请勿见怪

package cn.cherish.common;import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;/*** 项目名称:springmvc_hibernate* 类名称:MailUtil* 类描述:* 创建人:Cherish* 联系方式:785427346@qq.com* 创建时间:2016年4月22日 下午3:51:48* @version 1.0*/
public class MailUtil {private static final String HOST = "smtp.qq.com";private static final String SMTP = "smtp";private static final String USERNAME = "785427346@qq.com";private static final String PASSWORD = "xxxxxxxxxx";private static final int PORT = 587;//587/465private static final String DEFAULTENCODING = "UTF-8";private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();private static Properties prop = new Properties();static{// 设定mail serversenderImpl.setHost(HOST);senderImpl.setProtocol(SMTP);senderImpl.setUsername(USERNAME);senderImpl.setPassword(PASSWORD);senderImpl.setPort(PORT);senderImpl.setDefaultEncoding(DEFAULTENCODING);// 设定propertiesprop.put("mail.smtp.auth", "true");prop.put("mail.smtp.timeout", "25000");//设置调试模式可以在控制台查看发送过程prop.put("mail.debug", "true");senderImpl.setJavaMailProperties(prop);}public static void main(String args[]) {// 设置收件人,寄件人 用数组发送多个邮件
//      String[] array = new String[] {"88888@qq.com","666666@qq.com","999999999@qq.com",USERNAME};String[] array = new String[] {USERNAME};String subject = "Cherish内嵌图片、音乐的邮件";//      StringBuffer sb = new StringBuffer();
//      try {//          URL url = new URL("http://www.imooc.com/");//http://android-studio.org/
//
//          URLConnection conn = url.openConnection();
//          InputStream is = conn.getInputStream();
//
//          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//
//          String string = null;
//          while ((string = reader.readLine()) != null) {//              sb.append(string);
//          }
//
//          //System.out.println(sb.toString());
//
//      } catch (Exception e) {//          e.printStackTrace();
//      }
//
//      boolean result = htmlMail(array, subject, sb.toString());String filePath = "E:/javaxmail.png";String html = "<html><head>"+"</head><body>"+"<audio src='http://m10.music.126.net/20160422225433/25b43b999bcdaf3425b9194514340596/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3' autoplay='autoplay' controls='controls' loop='-1'>爱你</audio>"+"<h1>Hello,Nice to meet you!</h1>"+"<span style='color:red;font-size:36px;'>并摸了一把你的小奶</span>"+"<img src='cid:javaxmail.png'>"+"</body></html>";boolean result = inlineFileMail(array, subject, html, filePath);if (result) {System.out.println("发送邮件成功。。。。");}}/*** 发送简单邮件* @param to 收件人邮箱* @param subject 主题* @param content 内容* @return*/public static boolean singleMail(String to, String subject, String content){String[] array = new String[] {to};return singleMail(array, subject, content);}/*** 发送简单文本邮件* @param to 收件人邮箱数组* @param subject 主题* @param content 内容* @return*/public static boolean singleMail(String[] to, String subject, String content){boolean result = true;SimpleMailMessage mailMessage = new SimpleMailMessage();// 设置收件人,寄件人 用数组发送多个邮件mailMessage.setTo(to);mailMessage.setFrom(USERNAME);mailMessage.setSubject(subject);mailMessage.setText(content);// 发送邮件try {senderImpl.send(mailMessage);} catch (MailException e) {e.printStackTrace();result = false;}return result;}/*** 发送html邮件* @param to 收件人* @param subject 主题* @param html html代码* @return*/public static boolean htmlMail(String[] to, String subject, String html){boolean result = true;MimeMessage mailMessage = senderImpl.createMimeMessage();  MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);  try {// 设置收件人,寄件人 用数组发送多个邮件messageHelper.setTo(to);messageHelper.setFrom(USERNAME);messageHelper.setSubject(subject);// true 表示启动HTML格式的邮件  messageHelper.setText(html, true);  // 发送邮件senderImpl.send(mailMessage);} catch (MessagingException e) {result = false;e.printStackTrace();}return result;}/*** 发送内嵌图片的邮件   (cid:资源名)* @param to 收件人邮箱* @param subject 主题* @param html html代码* @param imgPath 图片路径* @return*/public static boolean inlineFileMail(String[] to, String subject, String html, String filePath){boolean result = true;MimeMessage mailMessage = senderImpl.createMimeMessage();  try {//设置true开启嵌入图片的功能MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);  // 设置收件人,寄件人 用数组发送多个邮件messageHelper.setTo(to);messageHelper.setFrom(USERNAME);messageHelper.setSubject(subject);// true 表示启动HTML格式的邮件  messageHelper.setText(html, true);  FileSystemResource file = new FileSystemResource(new File(filePath));  messageHelper.addInline(file.getFilename(), file);  // 发送邮件senderImpl.send(mailMessage);} catch (MessagingException e) {result = false;e.printStackTrace();}return result;}/*** 发送带附件的邮件* @param to* @param subject* @param html* @param filePath* @return*/public static boolean attachedFileMail(String[] to, String subject, String html, String filePath){boolean result = true;MimeMessage mailMessage = senderImpl.createMimeMessage();  try {// multipart模式 为true时发送附件 可以设置html格式MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");  // 设置收件人,寄件人 用数组发送多个邮件messageHelper.setTo(to);messageHelper.setFrom(USERNAME);messageHelper.setSubject(subject);// true 表示启动HTML格式的邮件  messageHelper.setText(html, true);  FileSystemResource file = new FileSystemResource(new File(filePath));  // 这里的方法调用和插入图片是不同的。  messageHelper.addAttachment(file.getFilename(), file);// 发送邮件senderImpl.send(mailMessage);} catch (MessagingException e) {result = false;e.printStackTrace();}return result;}}

温馨提示:

<img src='cid:javaxmail.png'>
这是内嵌图片的方式 javaxmail.png 要和 messageHelper.addInline(file.getFilename(), file); 这里的 file.getFilename() 相一致就可以显示

现在只差一步了,那就是Ctrl + F11,有不当之处敬请提出,共同进步

**

使用javax.mail发邮件代码

**

package cn.cherish.utils;import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;/*** 项目名称:springmvc_hibernate * 类名称:EmailUtil * 类描述:发送邮件工具类 * 创建人:Cherish* 联系方式:785427346@qq.com * 创建时间:2016年4月23日 上午9:48:21* @version 1.0*/
public class EmailUtil {// properties配置文件地址//private static final String PROPERTIES_PATH = "standard_data.properties";private static Session session;private static Properties props = new Properties();private static final String HOST = "smtp.qq.com";private static int PORT = 587;private static final String isAUTH = "true";private static final String FROM = "785427346@qq.com";private static final String USERNAME = "785427346@qq.com";private static final String PASSWORD = "xxxxxxxxxxxxxxxx";private static final String TIMEOUT = "25000";private static final String DEBUG = "true";// 初始化sessionstatic {props.put("mail.smtp.host", HOST);props.put("mail.smtp.port", PORT);props.put("mail.smtp.auth", isAUTH);props.put("fromer", FROM);props.put("username", USERNAME);props.put("password", PASSWORD);props.put("mail.smtp.timeout", TIMEOUT);props.put("mail.debug", DEBUG);session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(USERNAME, PASSWORD);}});}public static void main(String[] args) {try {String html = "<html><head>"+"</head><body>"+"<audio src='http://219.128.78.22/m10.music.126.net/20160423105749/3cee5688a7dc87d28a265fd992ecb0a2/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3?wshc_tag=1&wsts_tag=571aded1&wsid_tag=b73f773e&wsiphost=ipdbm' autoplay='autoplay' controls='controls' loop='-1'>爱你</audio>"+"<video controls='controls'>"+"<source src='http://v2.mukewang.com/45ad4643-87d7-444b-a3b9-fbf32de63811/H.mp4?auth_key=1461379796-0-0-e86cefa71cef963875fd68f8a419dd8a' type='video/mp4' />"+"Your browser does not support the video tag."+"</video>"+"<h1>Hello,nice to fuck you!</h1>"+"<span style='color:red;font-size:36px;'>并抓了一把你的小鸡鸡</span>"+"</body></html>";//sendEmail("785427346@qq.com", "yeah", html, true);sendFileEmail("785427346@qq.com", "yeah", html, new File("E:/xiaoming.zip"));} catch (Exception e) {e.printStackTrace();}}/*** * @Title sendEmail* @Description 通过isHtml判断发送的邮件的内容* @param to 邮件接收者* @param content 邮件内容* @param isHtml 是否发送html* @throws MessagingException* @throws IOException* @throws FileNotFoundException* @throws EmailException*/public static void sendEmail(String to, String title, String content, boolean isHtml)throws FileNotFoundException, IOException, MessagingException {String fromer = props.getProperty("fromer");if (isHtml) {sendHtmlEmail(fromer, to, title, content);} else {sendTextEmail(fromer, to, title, content);}}// 发送纯文字邮件public static void sendTextEmail(String from, String to, String subject, String content)throws FileNotFoundException, IOException, MessagingException {Message message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.setRecipient(RecipientType.TO, new InternetAddress(to));message.setSubject(subject);message.setText(content);message.setSentDate(new Date());Transport.send(message);}// 发送有HTML格式邮件public static void sendHtmlEmail(String from, String to, String subject, String htmlConent)throws FileNotFoundException, IOException, MessagingException {Message message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.setRecipient(RecipientType.TO, new InternetAddress(to));message.setSubject(subject);message.setSentDate(new Date());Multipart multi = new MimeMultipart();BodyPart html = new MimeBodyPart();html.setContent(htmlConent, "text/html; charset=utf-8");multi.addBodyPart(html);message.setContent(multi);Transport.send(message);}// 发送带附件的邮件public static void sendFileEmail(String to, String subject, String htmlConent, File attachment)throws FileNotFoundException, IOException, MessagingException {Message message = new MimeMessage(session);String fromer = props.getProperty("fromer");message.setFrom(new InternetAddress(fromer));message.setRecipient(RecipientType.TO, new InternetAddress(to));message.setSubject(subject);message.setSentDate(new Date());// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件Multipart multipart = new MimeMultipart();// 添加邮件正文BodyPart contentPart = new MimeBodyPart();contentPart.setContent(htmlConent, "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);}message.setContent(multipart);Transport.send(message);}}

java spring 开启SMTP服务发送QQ邮件相关推荐

  1. JavaMail 使用POP3/SMTP服务发送QQ邮件

    目录 一.说明 二.理解 三.实现 1.导入jar包 2.用户认证 3.发送邮件 创建步骤 简单的Email 带HTML的E-mail 带图片的Email 包含附件的邮件 一.说明 邮件服务器 为用户 ...

  2. Python利用POP3/SMTP服务自动发送qq邮件

    自动发送qq邮件的两种方法 第一种:POP3/SMTP服务发送qq邮件 废话不多说,直接上代码. # coding:utf-8 import smtplib from email.mime.text ...

  3. 通过QQ邮箱的SMTP服务器发送QQ邮件至163邮箱提示“发送邮件失败”的解决方案(三种可能性,不妨一试)...

    IDE:Visual Studio 2010[C#] + .NET 4.0框架 引用.NET 4.0框架的System.Net.Mail命名空间开发发送邮件的程序.发送方:QQ邮箱 接收方:163邮箱 ...

  4. Java 通过SMTP实现发送QQ邮件

    在eclipse中创建项目,并把javax.amil.jar和commons-email-1.5,jar复制到项目中 链接:https://pan.baidu.com/s/1sQjA1GEpKi6IJ ...

  5. python3:利用SMTP协议发送QQ邮件+附件

    转载请表明出处:https://www.cnblogs.com/shapeL/p/9115887.html 1.发送QQ邮件,首先必须知道QQ邮箱的SMTP服务器 http://service.mai ...

  6. Simple Java Mail的使用,发送qq邮件

    Simple Java Mail的使用,发送qq邮件 第一步 开启SMTP服务 第二步 导入jar包 第三步 简单的使用 四 集中配置,批量发送 第一步 开启SMTP服务 打开qq邮箱,设置-账户 开 ...

  7. java怎么发qq邮件_java代码如何发送QQ邮件

    近来想写一个qq之间互相发送邮件的工具.奈何一直报错服务错误: org.apache.commons.mail.EmailException: Sending the email to the fol ...

  8. 发送QQ邮件(Java)

    1 开启SMTP服务 登录QQ邮箱,点击设置,切换到账户界面 开启SMTP服务,点击开启 使用密保手机输入"配置邮件客户端"至1069070069手机号,然后点击我已发送按钮,确认 ...

  9. java 163邮件发送 ssl协议失败_163邮箱开启SMTP服务发送邮件出现535错误的解决方法...

    摘要: 用老的163邮箱可以直接设置SMTP发送邮件,使用新注册的却不行!折腾了几个小时后终于找到了方法,然后destoon就可以成功的发送邮件了..... 好久没有写关于destoon网站管理系统的 ...

最新文章

  1. 50万奖金+京东数科offer,JDD-2018全球总决赛冠军诞生
  2. 两个简单的动态规划问题,0-1背包和最大不相邻数累加和,附递归c代码
  3. 出现的是乱码_cad状态栏出现了方框乱码怎么办?
  4. UITableView 禁止下拉
  5. 【15】淘宝sdk——入门实战之header.php制作(三)
  6. Unity 3D 萌萌哒三消游戏《宝石消消乐》源码
  7. FFmpeg的一些结构与函数
  8. 开源盛世:谈谈开源代码的使用与安全风险
  9. 2020-09-08风扇并联与串联应用学习
  10. Android AB系统ota更新
  11. Catia V5-6R2016软件安装教程——附下载地址
  12. centos7.6修改分辨率
  13. 造车 8 年,苹果“认输”了:放弃 L 5 级全自动驾驶,售价低于 70 万,将于 2026 年推出...
  14. VMware vSphere的相关知识
  15. Unity Application Block 1.2 学习笔记 [转]
  16. 常用联网方式和名词解释
  17. 【图像检测】基于AC算法实现图像显著性检测附matlab代码
  18. matlab关闭文本,matlab parpool 关闭
  19. 乘法逆元的三种求解方法
  20. 天梯赛 最佳情侣身高差

热门文章

  1. mysql distinct 失效_Mysql DISTINCT问题
  2. python的loc函数_如何在pandas中使用loc、iloc函数进行数据索引(入门篇)
  3. 【tyvj】P2065 「Poetize10」封印一击(贪心+线段树/差分)
  4. 2019.09.15 多校联合训练(提高组)
  5. 2020牛客寒假算法基础集训营4
  6. Web网络编程第一次试验:ASP.NET4.5标准控件和窗体验证
  7. 语音合成(speech synthesis)方向一:双重学习Dual Learning
  8. linux指令_肖长青
  9. java list contains_Java List containsAll()用法及代码示例
  10. 查询数据库中的第10到20条记录