今天忙了一天总算有点收获
介绍几种
First: 这是小文件发送方案:
public void GetYan1(){
String uname=request.getParameter("uname");
User listu=null;
JsonModel jm=new JsonModel();
listu=userBiz.findAllbyunamey(uname);
if(listu!=null){
String number=listu.getUphone();
number+="@sohu.com";
number="[email protected]";
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts;
try {
ts = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
ts.connect("smtp.sohu.com", "ppag940065f19752", "yaobo1195022367");
//4、创建邮件
Message message = createSimpleMail(session,number);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jm.setCode(Integer.parseInt(content));
}else{
jm.setCode(0);
}
cs.outData(response, jm);
}
public static MimeMessage createSimpleMail(Session session1,String number)
throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session1);
content=String.valueOf((int)(Math.random()*9000+1000));
//指明邮件的发件人
message.setFrom(new InternetAddress(" [email protected] "));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress(number));
//邮件的标题
message.setSubject("来自厚学网的验证信息");
//邮件的文本内容
message.setContent(content, "text/html;charset=UTF-8");
//返回创建好的邮件对象
return message;
}
Second 这是带附件的方案
package com.yc.email;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class Send {
private String eserverhost="";
private String emailname="";
private String emailpwd="";
private String affix = ""; //附件地址
private String affixName = ""; //附件名称
private static MimeMessage message;
private Session session;
private static Properties properties = new Properties();
private Transport transport;
public Send(boolean debug){
eserverhost = properties.getProperty("smtp.163.com");
emailname = properties.getProperty( "[email protected]" );
emailpwd = properties.getProperty("gzrfpblhqtxjazbn");
properties.put("mail.smtp.host","smtp.163.com");
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties,null);
session.setDebug(debug);// 开启后有调试信息
message = new MimeMessage(session);
}
public String send(String emailnames,String receiver,String subject,String text,String affix,String affixName ){
try {
// 发件人
InternetAddress from = new InternetAddress(emailnames);
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiver);
message.setRecipient(Message.RecipientType.TO, to);
// 邮件主题
message.setSubject(subject);
// 向reciever对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(text, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
BodyPart messageBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(affix);
//添加附件的内容
messageBodyPart.setDataHandler(new DataHandler(source));
//添加附件的标题
//这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
// messageBodyPart.setFileName("=?GBK?B?"+enc.encode(affixName.getBytes())+"?=");
// multipart.addBodyPart(messageBodyPart);
messageBodyPart.setFileName(MimeUtility.encodeWord(affixName,"utf-8",null));
multipart.addBodyPart(messageBodyPart);
// 将multipart对象放到message中
message.setContent(multipart);
//关键代码
message.setFrom(new InternetAddress("[email protected]")); //[email protected]
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect("smtp.163.com","[email protected]", "gzrfpblhqtxjazbn"); ///nlbgikphduvkibwz
// 发送
transport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
e.printStackTrace();
System.out.println("错误");
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
System.out.println("yaobo"+text.toString());
return text;
}
public static void main(String[] args) {
Send email=new Send(true);
email.send("[email protected]","[email protected]","sdas","asdasdasd","F:/1.png","1.png");
}
}
Third Spring 模板发送方案
public void sendOpEmail(final String uemail,final String uname,final String content) {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(d);
MimeMessageHelper message = new MimeMessageHelper(mimeMessage,"utf-8");
message.setSubject("[厚学网] 修改密码通知");
message.setTo(uemail); //接收方邮箱
message.setFrom("[email protected]"); //发送方邮箱
//放到模板中的参数
Map model = new HashMap();
model.put("uname", uname);
model.put("content", content);
model.put("time", time);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"com/houxue/web/view/vm/depositewithdraw.vm","utf-8" ,model);
message.setText(text, true);
}
};
this.mailSender.send(preparator);
}
xml配置
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com" />
<property name="username" value="15574769400" />
<property name="password" value="gzrfpblhqtxjazbn" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">trueprop>
props>
property>
bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
value>
property>
bean>
模板
<html>
<head>
<meta charset="UTF-8">
<title>[厚学网] 修改密码通知title>
head>
<body>
亲爱的用户${uname}:您好!
您的厚学帐号于${time}需修改密码,如非本人操作,则密码可能已经泄露,建议查看您的账户
<br/>
<h2 style="color:red">您的验证码为:h2>
<a style="font-weight:bold;color:green">${content}a>
<br/>
<br/>
<a>我们将为你提供最好的学习平台a>
<br/>
<a>分享您认为最好的内容<a>
<br>
<a>同时还为您提供业界新闻、人才、外包 等等更多优质的服务<a>
<br/>
WWW.houxe.com - 中国最好的学习,为喜爱学习的人才提供最全面的信息传播和服务平台
body>
html>