java smtp协议_java发送邮箱(SMTP协议)

public class EmailUtil {

// 邮件主题

static String title = "";

// 被发送的的用户邮箱

static String user= "";

// 内容

static String content = "";

// 验证码有效时间(秒)

static int session;

// 发件人地址

static String fromAddress;

// 发送邮件的服务器

static String host;

// 发送邮箱账户

static String userName;

// 发送邮箱密码

static String passsWord;

public static void send(String user){

if(getProperties()){

// 内容

String content = content1+verifyCode+content2;

//1、创建连接对象

Properties props = new Properties();

//1.1设置邮件发送的协议

props.put("mail.transport.protocol" , "SMTP");

//1.2设置发送邮件的服务器

try {

props.put("mail.smtp.host" , host);

//1.3需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)

props.put("mail.smtp.auth" , "true");

//1.5认证信息

Session session=Session.getInstance(props , new Authenticator() {

protected PasswordAuthentication

getPasswordAuthentication(){

//用户密码

return new PasswordAuthentication(userName , passsWord);

}

});

//      2、创建邮件对象

Message message = new MimeMessage( session );

//2.1设置发件人

message.setFrom( new InternetAddress(fromAddress) );

//2.2设置收件人

message.setRecipient(RecipientType.TO , new InternetAddress( user));

//2.3设置抄送者(PS:没有这一条网易会认为这是一条垃圾短信,而发不出去)

// message.setRecipient(RecipientType.CC , new InternetAddress("yu449212849@163.com"));

//2.4设置邮件的主题

message.setSubject(title);

//2.5设置邮件的内容

message.setContent(""+content+"", "text/html;charset=utf-8");

//    3、发送邮件

Transport.send(message);

} catch (AddressException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (MessagingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

public static boolean getProperties() {

String classPath = EmailUtil.class.getResource("EmailUtil.class")

.toString();

System.out.println("classPath:" + classPath);

try {

String classFilePath = classPath;

if (classFilePath.startsWith("file:/"))

classFilePath = classFilePath.substring(6);

classFilePath = classFilePath.replace("%20", " ");

int pos = classFilePath.lastIndexOf(47);

String file = classFilePath.substring(0, pos + 1);

file = file + "email.properties";

InputStream is;

is = new FileInputStream(file);

Properties p = new Properties();

p.load(is);

title = p.getProperty("title");

content = p.getProperty("content1");

fromAddress = p.getProperty("fromAddress");

host = p.getProperty("host");

userName = p.getProperty("userName");

passsWord = p.getProperty("passsWord");

return true;

} catch (Exception e) {

e.printStackTrace();

return false;

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值