SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。
SMTP服务器默认端口25
POP3协议
POP3(Post Office Protocol-Version 3)即邮局协议版本3
本协议主要用于支持使用客户端远程管理在服务器上的电子邮件
POP3服务器默认端口110
以QQ邮箱为例发送邮件
1.开启服务并获取授权码
2.编写Java代码
SendEmail.java
importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;publicclassSendEmail{publicstaticvoidmain(String[]args){// 收件人电子邮箱Stringto="619***897@qq.com";// 发件人电子邮箱Stringfrom="2811***772@qq.com";// 指定发送邮件的主机为 smtp.qq.comStringhost="smtp.qq.com";//QQ 邮件服务器// 获取系统属性Propertiesproperties=System.getProperties();// 设置邮件服务器properties.setProperty("mail.smtp.host",host);//用户密码认证properties.put("mail.smtp.auth","true");//配置SSL加密方式properties.put("mail.smtp.port","587");//调试模式//properties.put("mail.debug", "true");// 获取默认session对象Sessionsession=Session.getDefaultInstance(properties,newAuthenticator(){publicPasswordAuthenticationgetPasswordAuthentication(){returnnewPasswordAuthentication("2811***772@qq.com","ksva********dcgj");//发件人邮件用户名、密码}});try{// 创建默认的 MimeMessage 对象MimeMessagemessage=newMimeMessage(session);// Set From: 头部头字段message.setFrom(newInternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,newInternetAddress(to));// Set Subject: 头部头字段message.setSubject("邮件消息标题");// 设置消息体message.setText("邮件消息具体内容");// 发送消息Transport.send(message);System.out.println("邮件发送成功");}catch(MessagingExceptionmex){mex.printStackTrace();}}}
3.查看邮箱可以看到收到测试的邮件信息
问题1
javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28