本文實例講述了java使用spring實作發送mail的方法。分享給大家供大家參考。具體如下:
這裡借鏡別人的優點以及自己的一些加工,寫出如下程式碼:
package test;import java.util.Properties;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import org.springframework.mail.SimpleMailMessage;import org.springframework.springframework.mail.SimpleMailMessage;Sender org.springframework.javamail.javamail. org.springframework.mail.javamail.MimeMessageHelper;/** * 本類別測試簡單郵件直接用郵件發送* * @author Administrator * */public class SingleMailSend { public static void main(String args[]) throws MessagingException { JavaMailSImplception { = new JavaMailSenderImpl(); //設定郵件伺服器//senderImpl.setHost("smtp.163.com"); senderImpl.setHost("smtp.qq.com"); // 建立郵件訊息// SimpleMailMessage mailMessage = new SimpleMailMessage(); MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true,"utf-8"); // 設定收件者,群發郵件String[] array = new String[] {"[email protected]","[email protected]" }; helper.setTo(array); //mailMessage.setTo("[email protected]"); helper.setFrom("[email protected]"); helper.setSubject("這是我的主題!"); helper.setText("<p stylestyle ='color:red;'>這是我的內容! </p>",true); //新增附件ClassPathResource resource = new ClassPathResource("test.jpg"); helper.addAttachment("hello.jpg", resource);// 依照自己的狀況,設定username // senderImpl.setUsername("[email protected]"); senderImpl.setUsername("[email protected]"); senderImpl.setPassword("你的密碼"); // 依照自己的狀況, 設定password /* Properties prop = new Properties(); prop.put(" mail. smtp.auth ", " true "); //將這個參數設為true,讓伺服器進行認證,認證使用者名稱和密碼是否正確prop.put(" mail.smtp.timeout ", " 25000 "); senderImpl.setJavaMailProperties(prop);*/ // 傳送郵件senderImpl. send(mailMessage); System.out.println(" 郵件發送成功.. "); }}
希望本文所述對大家的java程式設計有幫助。