您的位置:首页 > 编程语言 > Java开发

javamail使用教程,正确代码,各种错误及解决方案

2016-11-11 10:10 543 查看
在实现javamail之前,你需要将程序用到的两个jar包导进来。activation.jar和mail.jar

按照流程,我走了好多遍,终于把它给走通。下面我总结了可能出现的各种原因

错误一:535 5.7.8 authentication failed   身份认证失败   原因:(1)可能是用户名密码错误(2)主机名错误

错误二:com.sun.mail.smtp.SMTPSenderFailedException: 553 Envolope sender mismatch with login user.. :登录人和信封上的发送人不匹配  原因:检查你的发件人邮箱和发件人用户名,密码

错误三:javax.mail.SendFailedException: Invalid Addresses;

  nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 501 Syntax error :错误的地址  原因:收件人邮箱格式错误

下面是我的代码,是可以跑通的

package tm.change.test;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.junit.Test;

public class test {
@Test
public void a(){
//(1)建立和邮件服务器的回话
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");//协议
props.setProperty("mail.smtp.host", "smtp.sina.com");//主机名
props.setProperty("mail.smtp.auth", "true");//是否开启权限控制
props.setProperty("mail.debug", "true");//是否打印发送时的信息
Session session = Session.getInstance(props);

//2)创建邮件
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress("hxsf1@sina.com"));
msg.setSubject("这是一封来自java的邮件");//标题
msg.setText("你好,点击如下连接激活帐号,如果不能点击请复制连接到浏览器地址栏访问:http://localhost:8080/estore/ActiveServlet?activecode=");
msg.setRecipient(RecipientType.TO, new InternetAddress("receiver@qq.com"));//收件人

//3)发送邮件
Transport trans = session.getTransport();
trans.connect("hxsf1","QWErty");//发件人的用户名和密码
trans.sendMessage(msg, msg.getAllRecipients());
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//发件人邮箱

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐