java使用smtp发送邮件问题


原先使用smtp通过邮箱发送邮件不需要认证,但是后来发现如果使用的是QQ邮箱会报认证失败的异常。原来QQ邮箱是需要ssl认证的,需要先到QQ邮箱里的 设置--账户--POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 开通POP3/SMTP服务获得授权码,在transport.connect的时候传的是这个授权码,并且需要在props里添加几个参数,于是在原来的基础上做了修改加了一个了方法,QQ邮箱也可以发送了.


开通SMTP服务



props添加代码

props.put("mail.smtp.ssl.enable", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.port", "465");

java使用smtp发送邮件代码

import java.util.Properties;
import java.util.StringTokenizer;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail {
    String      SMTPServer ;
    String      user ;
    String      password ;
    Properties  props = new Properties();
    Session     sendMailSession;
    Store       store;
    Transport   transport;
    MimeMessage newMessage;
    public SendMail(String SMTPServer,String user,String password){
    	this.SMTPServer = SMTPServer;
    	this.user       = user;
    	this.password   = password;
    	try {    
            props.put("mail.smtp.host", SMTPServer);
            props.put("mail.smtp.auth", "true");
           
            qqMailConf(SMTPServer, props);
            
            sendMailSession=Session.getInstance(props, null);
           
            sendMailSession.setDebug(false);
            newMessage = new MimeMessage(sendMailSession); 
        }catch(Exception e) {
		    System.err.println(e.getMessage());
		}
	}
    
   /**
    * qq邮箱设置
    */
   public void qqMailConf(String SMTPServer, Properties props){
	   if(SMTPServer.indexOf("smtp.qq.com")!=-1){
		   props.put("mail.smtp.ssl.enable", "true");		   
		   props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		   props.setProperty("mail.smtp.socketFactory.port", "465");
	   }
	   
   }
    
	/**
      * 下面是邮件发送的方法 
      * 参数注释
      * from:   发信人邮箱地址
      * to:     收信人邮箱地址
      * cc:     抄送人     可以为null
      * bcc:    暗送人        可以为null
      * subject:主题
      * content:内容
      */
    public  String send(String from,String to,String cc,String bcc,String subject,String content) {
        try {
        	System.out.println("hhhh");
            newMessage.setFrom(new InternetAddress(from, ""));
            newMessage.setSubject(subject);
            newMessage.setSentDate(new java.util.Date());
            StringTokenizer tokenTO     = new StringTokenizer(to, ",");        
            InternetAddress[] addrArrTO = new InternetAddress[tokenTO.countTokens()];
            int i = 0;
            while(tokenTO.hasMoreTokens()) {
                addrArrTO[i] = new InternetAddress(tokenTO.nextToken().toString());
                i++;
            }
            newMessage.saveChanges();
            
            transport = sendMailSession.getTransport("smtp");
            transport.connect(SMTPServer, user, password);
            if(i>0)
                 newMessage.setRecipients(Message.RecipientType.TO, addrArrTO);
            else   
                if(to!=null) newMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                
            if(cc!=null)  
               newMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            if(bcc!=null) 
               newMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
            
            newMessage.setText(content);
            transport.sendMessage(newMessage, newMessage.getAllRecipients());

        }
        catch(Exception e) {
        	e.printStackTrace();
            return e.toString();//邮件发送失败
        }
        return "OK";           //邮件发送成功
     }   
    

    public static void main(String[] arg) {
    	SendMail sendMail = new SendMail("smtp.qq.com", "*******@qq.com", "..授权码..");
    	for (int i = 0; i < 1; i++) {
    	  String msg = sendMail.send("*******@qq.com","test@qq.com",null,null,"测试subject" + 1,"测试contents");
          System.out.println("Message:"+ i + msg);
    	}
    }
    	
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值