java傳送郵件

久夢歌行發表於2014-12-12
<span style="white-space:pre">	</span>@Test
	public void fun() throws AddressException, MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		
		//發件郵箱驗證
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("qq83986976", "3854928");
			}
		};
			
		//得到session
		Session session = Session.getInstance(props, auth);
		//建立MimeMessage
		MimeMessage msg = new MimeMessage(session);
		//設定發件人
		msg.setFrom(new InternetAddress("qq83986976@163.com"));
		/*
		 * 設定收件人
		 * to收件人
		 * cc抄送
		 * bcc暗送
		 */
		msg.setRecipients(RecipientType.TO, "83986976@qq.com");
		
		msg.setSubject("測試郵件");
		msg.setContent("郵件測試", "text/html;charset=utf-8");
		
		Transport.send(msg);
	}

傳送帶有附件的郵件

	public void fun2() throws AddressException, MessagingException, IOException {
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("qq83986976", "3854928");
			}
		};
			
		//得到session
		Session session = Session.getInstance(props, auth);
		//建立MimeMessage
		MimeMessage msg = new MimeMessage(session);
		//設定發件人
		msg.setFrom(new InternetAddress("qq83986976@163.com"));
		msg.setRecipients(RecipientType.TO, "83986976@qq.com");
		msg.setSubject("我的附件測試");
		
		/*
		 * 傳送附件,
		 * 1多部件的部件內容,MimeMultipart
		 * 2個主體
		 */
		MimeMultipart list = new MimeMultipart();
		//建立MimeBodyPart
		MimeBodyPart part1 = new MimeBodyPart();
		part1.setContent("附件郵件","text/html;charset=utf-8");
		//新增部分
		list.addBodyPart(part1);
		
		MimeBodyPart part2 = new MimeBodyPart();
		part2.attachFile(new File("F:/黨員.png"));
		//顯示在附件上,並處理亂碼
		part2.setFileName(MimeUtility.encodeText("黨員.png"));
		list.addBodyPart(part2);
		
		msg.setContent(list);
		
		Transport.send(msg);
	}


相關文章