spring 发简单Email,带附件Email,HTML格式Email

public static void main(String[] args) throws Exception
	{

		JavaMailSenderImpl senderMail = new JavaMailSenderImpl();
		
		// 设定 Mail Server
		senderMail.setHost("smtp.163.com");
		senderMail.setPort(25);

		Properties prop = new Properties();
		prop.setProperty("mail.smtp.auth", "true");

		// SMTP验证时,需要用户名和密码
		senderMail.setUsername("[email protected]");
		senderMail.setPassword("***");
		senderMail.setJavaMailProperties(prop); //如果要密码验证,这里必须加,不然会报553错误

		// 建立简单的邮件信息
		SimpleMailMessage mailMessage = new SimpleMailMessage();

		// 设定收件人、寄件人、主题与内文
		mailMessage.setTo("[email protected]");
		mailMessage.setFrom("[email protected]");//这里必须和用户名一样,不然会报553错误
		mailMessage.setSubject("小子");
		mailMessage.setText("小子想死吧。。。。。。!!");

		// 传送邮件
		senderMail.send(mailMessage);
		
		
		

		//发送HTML格式的邮件		
		//建立邮件信息,可发送HTML格式
		MimeMessage mimeMessage = senderMail.createMimeMessage(); //MimeMessage-->java的
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"GBK"); // MimeMessageHelper-->spring的  不加后面两个参数会乱码

		//设置收件人,主题,内容
		messageHelper.setSubject("Hello! ");
		messageHelper.setFrom("[email protected]");
		messageHelper.setTo("[email protected]");
		
		StringBuffer str = new StringBuffer();
		str.append("<html><head></head><body><h1>Hello! 中文! </h1></body></html>");
		messageHelper.setText(str.toString(),true); //为true-->发送转义HTML

		//senderMail.send(mimeMessage);  //这个是不带附件的	
		
		//发送带附件的
		FileSystemResource file = new FileSystemResource(new File("E:\\DevelopmentSoft\\spring-framework-3.0.5.RELEASE\\docs\\javadoc-api\\index.html"));
		messageHelper.addAttachment("index.html", file);
		
		senderMail.send(mimeMessage); //这个是发送带附件的

		System.out.println("邮件传送OK..");
	}

相关推荐