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

本文介绍使用JavaMail发送邮件的全过程,并解决常见错误,如身份验证失败、发送人不匹配及地址格式错误等问题。

在实现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();
		}//发件人邮箱
		
	 }
}



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值