- 相关推荐
Java认证考试: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,方便添加附件和内嵌资源等。
【Java认证考试:Spring实现邮件发送】相关文章:
Spring如何实现邮件发送07-26
JAVA认证考试细则06-10
java认证考试介绍07-31
sun java认证考试介绍10-23
JAVA认证考试费用06-25
java认证考试细则介绍08-19
Sun java认证考试答案11-06
JAVA考试认证经验分享08-22
Linux认证系统管理:linuxmail命令发送邮件失败09-21
Sun Java认证考试科目08-30