1.导入2个jar包,mail.jar,activation.jar
2.导入的jar包与myeclipse中自带的javaee 中的javaee.jar中的javax.activation包及javax.mail冲突,
解决办法如下:
在myeclipse中,点击window-preference-搜索框中输入lib,选中Library Sets,在右侧选择Javaee.jar-Add JAR/ZIP,然后选择用压缩程序打开,选择要移除的包,点击压缩程序上方的删除即可!
代码如下:
package test; import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType; import javax.mail.Authenticator;
import java.util.Properties;
/**
* 发送邮件
* @author admin
*
*/
public class JavaMail
{
public static void main(String[] args) throws AddressException, MessagingException
{
Properties props = new Properties();
//需要为props设置发送的主机和是否需要认证
// props.setProperty("mail.host", "localhost");//连接的服务器
props.setProperty("mail.host", "smtp.163.com");//连接的服务器
props.setProperty("mail.smtp.auth", "true");//是否需要认证 //创建一个对象Session
Session session = Session.getInstance(props, new Authenticator()
{ @Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("[email protected]", "wy5776402287"); } }); //创建一个邮件的对象
Message message = new MimeMessage(session); //设置发件人
message.setFrom(new InternetAddress("[email protected]"));
//设置收件人
message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
//设置邮件的主题
message.setSubject("一封激活邮件");
//设置邮件的正文 // message.setContent("激活邮件!", "text/plan");
message.setContent("<a href='http://www.baidu.com'>xxx,这是一封激活邮件!</a>", "text/html;charset=UTF-8");//加入超链接
//发送
Transport.send(message); }
}