zoukankan      html  css  js  c++  java
  • 关于使用Java Mail发邮件的问题

    今天做东西的时候突然遇到需要发邮件的问题,然后就使用SMTP协议进行邮件的发送。用了一个工具类简化邮件发送的功能,

    在这次试验中,我使用了自己的QQ邮箱进行发送邮件的发送者。

    public class MailUtils {
    
    	public static void sendMail(String email, String emailMsg)
    			throws AddressException, MessagingException {
    		// 1.创建一个程序与邮件服务器会话对象 Session
    
    		Properties props = new Properties();
    		props.setProperty("mail.transport.protocol", "SMTP");
    		props.setProperty("mail.host", "smtp.qq.com");
    		props.setProperty("mail.smtp.auth", "true");// 指定验证为true
    
    		// 创建验证器
    		Authenticator auth = new Authenticator() {
    			public PasswordAuthentication getPasswordAuthentication() {
    				return new PasswordAuthentication("QQ号码", "授权码");
    			}
    		};
    
    		Session session = Session.getInstance(props, auth);
    
    		// 2.创建一个Message,它相当于是邮件内容
    		Message message = new MimeMessage(session);
    
    		message.setFrom(new InternetAddress("QQ邮箱全部名称")); // 设置发送者
    
    		message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
    
    		message.setSubject("用户激活");
    		// message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
    
    		message.setContent(emailMsg, "text/html;charset=utf-8");
    
    		// 3.创建 Transport用于将邮件发送
    
    		Transport.send(message);
    	}
    }


    文章中牵涉到一个授权码的问题,发送邮件所使用的邮箱中需要设置将SMTP开启并获取授权码,在这里以QQ邮箱为例:

    什么是授权码,它又是如何设置?

    1、什么是授权码?
    授权码是QQ邮箱推出的,用于登录第三方客户端的专用密码。
    适用于登录以下服务:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务。
    温馨提醒:为了你的帐户安全,更改QQ密码以及独立密码会触发授权码过期,需要重新获取新的授权码登录。
     
    2、怎么获取授权码?
    先进入设置-》帐户页面找到入口,按照以下流程操作。
    (1)点击“开启”
    (2)验证密保
    (3)获取授权码

    这个时候如果使用163或者126邮箱的话,应该就可以实现发邮件的功能了,但是QQ邮箱的话这时会报一个这样的错误:


    提示说你的这个资源需要提供像ssl那样的加密方式,具体的请参考腾讯后面的那个网址。


    这个时候就需要在代码中提供ssl的加密方式了,

    添加后的代码为

    // 1.创建一个程序与邮件服务器会话对象 Session
    		//开启ssl加密
    		MailSSLSocketFactory sf = null;
    		try {
    			sf = new MailSSLSocketFactory();
    		} catch (GeneralSecurityException e) {
    			e.printStackTrace();
    		}
    		sf.setTrustAllHosts(true);
    		
    		Properties props = new Properties();
    		props.setProperty("mail.transport.protocol", "SMTP");
    		props.put("mail.smtp.ssl.enable", "true");
    		props.put("mail.smtp.ssl.socketFactory", sf);
    		props.setProperty("mail.host", "smtp.qq.com");
    		props.setProperty("mail.smtp.auth", "true");// 指定验证为true


    这样就可以在需要发送邮件的位置直接调用这个sendmail方法就可以实现发送邮件的功能了。

    个人见解,仅供参考...

  • 相关阅读:
    Qt编写控件属性设计器12-用户属性
    C#中通过三边长判断三角形类型(三角形测试用例)
    C#中通过Selenium定位<a>标签的问题
    SharePoint自动化系列——Manage "Site Subscriptions" using PowerShell
    SharePoint API测试系列——Records.BypassLocks测试
    SharePoint API测试系列——对Recorded Item做OM操作(委托的妙用)
    放松时刻——C#分割字符串
    链表——PowerShell版
    栈——PowerShell版
    队列——PowerShell版
  • 原文地址:https://www.cnblogs.com/kaifaxiaoliu/p/11980140.html
Copyright © 2011-2022 走看看