Java發送郵件(spring mail + apache mail)

以下是兩種郵件發送方式。 
給出的例子是是發送HTML格式帶附件的郵件。(普通文本格式的郵件基本上可以不關心,現在的郵件都是HTML格式的!) 

如果不要發送附件,只要發送單純的HTML郵件。只要把附件部分去掉即可 

/**
*用spring mail 發送郵件,依賴jar:spring.jar,activation.jar,mail.jar 
*/

public static void sendFileMail() throws MessagingException {
		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

		// 設定mail server
		senderImpl.setHost("smtp.126.com");
		senderImpl.setUsername("yuhan0");
		senderImpl.setPassword("******");
		// 建立HTML郵件消息
		MimeMessage mailMessage = senderImpl.createMimeMessage();
		// true表示開始附件模式
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

		// 設置收件人,寄件人
		messageHelper.setTo("[email protected]");
		messageHelper.setFrom("[email protected]");
		messageHelper.setSubject("測試郵件!");
		// true 表示啓動HTML格式的郵件
		messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>", true);

		FileSystemResource file1 = new FileSystemResource(new File("d:/logo.jpg"));
		FileSystemResource file2 = new FileSystemResource(new File("d:/讀書.txt"));
		// 添加2個附件
		messageHelper.addAttachment("logo.jpg", file1);
		
		try {
			//附件名有中文可能出現亂碼
			messageHelper.addAttachment(MimeUtility.encodeWord("讀書.txt"), file2);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new MessagingException();
		}
		// 發送郵件
		senderImpl.send(mailMessage);
		System.out.println("郵件發送成功.....");

	}



/**
*用apache commons-email 發送郵件
*依賴jar:commons-email.jar,activation.jar,mail.jar
*/
public static void sendMutiMessage() {

		MultiPartEmail email = new MultiPartEmail();
		String[] multiPaths = new String[] { "D:/1.jpg", "D:/2.txt" };

		List<EmailAttachment> list = new ArrayList<EmailAttachment>();
		for (int j = 0; j < multiPaths.length; j++) {
			EmailAttachment attachment = new EmailAttachment();
			//判斷當前這個文件路徑是否在本地  如果是:setPath  否則  setURL; 
			if (multiPaths[j].indexOf("http") == -1) {
				attachment.setPath(multiPaths[j]);
			} else {
				try {
					attachment.setURL(new URL(multiPaths[j]));
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
			attachment.setDisposition(EmailAttachment.ATTACHMENT);
			attachment.setDescription("Picture of John");
			list.add(attachment);
		}

		try {
			// 這裏是發送服務器的名字:
			email.setHostName("smtp.126.com");
			// 編碼集的設置
			email.setCharset("utf-8");
			// 收件人的郵箱				
			email.addTo("[email protected]");
			// 發送人的郵箱
			email.setFrom("[email protected]");
			// 如果需要認證信息的話,設置認證:用戶名-密碼。分別爲發件人在郵件服務器上的註冊名稱和密碼
			email.setAuthentication("yuhan0", "******");
			email.setSubject("這是一封測試郵件");
			// 要發送的信息
			email.setMsg("<b><a href=\"http://www.baidu.com\">郵件測試內容</a></b>");

			for (int a = 0; a < list.size(); a++) //添加多個附件   
			{
				email.attach(list.get(a));
			}
			// 發送
			email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
	}

原文地址:點擊打開鏈接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章