日期:2014-05-20 浏览次数:20791 次
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 levinhou */ 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 = "windhall@126.com";//接收者邮件 String fromMail = "123@126.com";//发送者邮件 String user = "windhall";//发送者用户 String pw = "xxxxxxxx";//发送者邮件密码 String fromName = "Chen";//发送者名字 String protocol = "smtp";//协议 String host = "smtp.126.com";//发送主机 String port = "25";//端口 String msg = "简单邮件发送。";//发送内容 String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port); System.out.println("邮件发送结果:" + ret); } }
import java.net.InetAddress; 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 SendMail { /** * 发送邮件测试 */ public static void main(String[] args) { try { // Get system properties Properties props = System.getProperties(); // 设置smtp邮件服务器 props.put("mail.smtp.host", "192.168.0.61"); props.setProperty("mail.smtp.port", "25"); props.put("mail.smtp.auth", false); // 取得连接 Session session = Session.getDefaultInstance(props, null); Transport transport = session.getTransport("smtp"); transport.connect(); // 邮件定义 MimeMessage mail = new MimeMessage(session); mail.addRecipient(Message.RecipientType.TO, new InternetAddress("To@test.com")); mail.setSubject("邮件标题……"); mail.setText("邮件正文……"); mail.setFrom(new InternetAddress("from@test.com")); transport.sendMessage(mail, mail.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } }