java代码简单实现发送邮件

1.首先需要下载 email相关jar包(activation.jar,mail.jar)。

2.由于公司不能上外网,我配置的为本地的邮箱服务器(易邮邮件服务器)。如果是互联网邮箱服务器

 pro.put("mail.smtp.host", "localhost"); localhost改为互联网服务器地址,如163邮箱就是smtp.163.com。

3.实现代码如下:(smtp是邮件发送的协议,pop3为邮箱的客户端获取邮件的协议,想了解可以百度下)

package sendemail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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;



public class test {
   public void sendemail(String to,String content,String title) throws AddressException, MessagingException{
	   String user ="bbb"; //邮箱账户
	   String pwd="123";   //邮箱登陆密码
	   Properties pro=new Properties();
	   pro.put("mail.smtp.host", "localhost"); //设置主机地址,此处为本机地址。如果使用163邮箱。该出应配置smtp.163.com
	   pro.put("mail.smtp.auth", true);  //是否开启验证

       Session instance = Session.getInstance(pro, new Authenticator() {
    	   @Override
    	protected PasswordAuthentication getPasswordAuthentication() {
    		// TODO Auto-generated method stub
    		return new PasswordAuthentication(user, pwd);
    	}
	});
       instance.setDebug(true);
       Message m=new MimeMessage(instance);
	   m.setFrom(new InternetAddress("bbb@sl.com")); //发件人
	   m.addRecipient(RecipientType.TO, new InternetAddress(to)); //收件人
	   m.setSubject(title);//设置标题
	   m.setContent(content,"text/html;charset=UTF-8"); //设置文本内容,和发送文本的格式
	   Transport.send(m);//调用该方法进行发送
   }
   public static void main(String[] args) {
	test t=new test();
	try {
		t.sendemail("aaa@sl.com", "内容", "标题");
	} catch (AddressException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (MessagingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

  运行之后,出现结果,如图:

 

转载于:https://www.cnblogs.com/leosajlei/p/5626056.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值