最近项目中要用到邮件服务,主体框架采用了spring mvc,spring很是强大的,本身有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 = "[email protected]";// 接收者邮件 String fromMail = "[email protected]";// 发送者邮件 String user = "[email protected]";// 发送者用户 String pw = "";// 发送者邮件密码 String fromName = "徐士刚";// 发送者名字 String protocol = "smtp";// 协议 String host = "smtp.bitbao.net";// 发送主机 String port = "25";// 端口 String msg = "大米我想你了";// 发送内容 String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port); System.out.println("邮件发送结果:" + ret); } }
有个问题就是:在别人的机器上总是报断开错误,导致连接失败,我机器上总是好使的。
暂时没时间研究,先上代码了。