- 相关推荐
Spring如何实现邮件发送
Spring提供了一个发送邮件的抽象层,使发送邮件实现非常简单。下面代码需要mail.jar包,如果服务器需要认证,必须加入如下加粗代码:
源文件:SendMail.java:
package mail;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Date;
/**
* @author chrischen
*/
public class SendMail {
//邮件发送器
public static String Sender(String subject, String msg, String sendTo, String fromMail, String user, String pw, String fromName, String protocol, String host, String port){
try{
final String username = user;
final String pass = pw;
//需要认证
Properties props = new Properties();
props.put(“mail.smtp.host”, host);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.transport.protocol”, protocol);
props.put(“mail.from”, fromMail);
//创建发送器
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(host);
sender.setUsername(username);
sender.setPassword(pass);
//创建消息
MimeMessage message = sender.createMimeMessage();
message.addHeader(“X-Mailer”, “Java Mailer”);
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(sendTo);
helper.setFrom(fromMail, fromName);
helper.setSubject(subject);
helper.setText(msg);
helper.setSentDate(new Date());
//开始发送
sender.setJavaMailProperties(props);
sender.send(message);
}catch(Exception e){
System.out.println(“Error:” + e);
return “Failure”;
}
return “Success”;
}
//测试
public static void main(String args[])throws Exception
{
String subject = “测试邮件”;//标题
String sendTo = “test@my.com”;//接收者邮件
String fromMail = “send@my.com”;//发送者邮件
String user = “send@my.com”;//发送者用户
String pw = “password”;//发送者邮件密码
String fromName = “Chen”;//发送者名字
String protocol = “smtp”;//协议
String host = “smtp.my.com”;//发送主机
String port = “25”;//端口
String msg = “简单邮件发送。”;//发送内容
String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port);
System.out.println(“邮件发送结果:” + ret);
}
}
使用MimeMessageHelper,可以实现Multipart email,方便添加附件和内嵌资源等。
【Spring如何实现邮件发送】相关文章:
如何用Word发送文件06-23
商务秘书如何让外商回复邮件06-28
如何实现员工的有效激励07-23
如何实现绿色环保装修11-02
如何更好地实现网站推广04-29
在word中如何实现自动续表06-23
如何实现有效的绩效沟通08-20
PHP中多态如何实现呢10-29
质量管理创新如何实现05-16
OA系统如何实现高效培训管理09-25