Spring邮箱发送

package com.lhh.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
private String mailServer="smtp.qq.com";
private String from="2694072078@qq.com";
private String to="3385351592@qq.com";
private String MailSubject="大白区块链";
private String MailContent="你好";
private String userName="2694072078";
//qq邮箱key
private String password="zojrqyuxvdpnddaexx";
public void send(){
try {
Properties p=System.getProperties();
p.put("mail.smtp.host", mailServer);
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.ssl.enable", "true");

EmailAuthentiactor authen=new EmailAuthentiactor(userName, password);

Session session=Session.getInstance(p, authen);

Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(MailSubject);
message.setContent(MailContent,"text/html;charset=utf8");

Transport t=session.getTransport("smtp");
t.send(message,message.getAllRecipients());
t.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}

 

 

 

 

 

 

 

 

 

 

package com.lhh.test;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class EmailAuthentiactor extends Authenticator{
private String userName;
private String password;
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public EmailAuthentiactor(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}

 

 

//test类

package com.lhh.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
/*EmailHtml e= (EmailHtml) app.getBean("mailHtml");
e.send();*/
//EmailAuthentiactor a=(EmailAuthentiactor) app.getBean("mailHtml");
Email a=new Email();
a.send();

System.out.println("发送成功!");
}
}

 

posted @ 2018-04-13 14:34  南城。  阅读(147)  评论(0编辑  收藏  举报