1. 程式人生 > >Java實現郵件傳送(很簡單)

Java實現郵件傳送(很簡單)

Java實現郵件傳送,需要指定郵件伺服器,和自己的郵箱賬號和密碼,謹記 自己的郵箱必須得到到客戶端授權碼,尤其是新開的郵箱,具體看程式碼,包括附件傳送

public class EmailUtils {
	
	private static String from = "";  //郵箱賬號
	private static String password = "";      //郵箱密碼或者授權碼
	private static String host = "";      //郵箱伺服器
	
	public static boolean sendMail(String receiver[],String subject,String msg,String filePath)  {
	    try {
	    	Properties properties = System.getProperties();
			properties.setProperty("mail.smtp.host", host);						//設定郵箱伺服器
			properties.put("mail.smtp.auth", "true");							//設定驗證
			properties.put("mail.smtp.ssl.enable", "true");
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
		    properties.put("mail.smtp.ssl.socketFactory", sf);
		    Session session = Session.getInstance(properties, new Authenticator() {
		    	public PasswordAuthentication getPasswordAuthentication() { 	// 郵箱伺服器賬戶、第三方登入授權碼
	                return new PasswordAuthentication(from, password); 			// 發件人郵件使用者名稱、密碼
	            }
			});
		    MimeMessage message = new MimeMessage(session);                               	 //建立郵件內容
			message.setFrom(new InternetAddress(from));
			if(receiver == null || receiver.length == 0) {
				return false;
			}
			InternetAddress ia[] = new InternetAddress[receiver.length];
			for(int i=0;i<receiver.length;i++) {
				ia[i] = new InternetAddress(receiver[i]);
			}
			message.addRecipients(Message.RecipientType.TO, ia);   //設定接受者 型別為傳送,也可改變型別為抄送 Message.RecipientType.CC
			message.setSubject(subject);
	        // 建立訊息部分
	        BodyPart messageBodyPart = new MimeBodyPart();
	        // 訊息
	        messageBodyPart.setText(msg);
	        // 建立多重訊息
	        Multipart multipart = new MimeMultipart();
	        multipart.addBodyPart(messageBodyPart);
	        // 附件部分
	        if(StringUtils.isNotBlank(filePath)) {
	        	File file = new File(filePath);
				if(!file.exists()) {
					return false;
				}
				String[] split = filePath.split("[/]");
				messageBodyPart = new MimeBodyPart();
		        DataSource source = new FileDataSource(filePath);
		        messageBodyPart.setDataHandler(new DataHandler(source));
		        messageBodyPart.setFileName(MimeUtility.encodeText(split[split.length-1],"utf-8","B"));	 	//設定附件名 防止中文亂碼
		        multipart.addBodyPart(messageBodyPart);
	        }
	        message.setContent(multipart);
	        Transport.send(message);
	        return true;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return false;
	}
}