代碼:
package com.dai.mail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class HtmlMessageSender { ??? String protocol = "smtp"; ??? String from = "15829004147@sina.cn"; ??? String to = "243047007@qq.com"; ??? String subject = "test"; ??? String body = " " + ??? ??? ??? "welcome to our website!"? + ??? ??? ??? ??? ??? "this is a test mail from sina!"; ??? /** ??? ?* create session and the session has been setted particular properties ??? ?* @return ??? ?*/ ??? public Session createSession() { ??? ??? Properties props = new Properties(); ??? ??? props.setProperty("mail.transport.protocol", protocol); ??? ??? /*必須將mail.smtp.auth屬性設置為true,SMTPTransport對象才會向SMTP服務器提交認證 ??? ??? ?* 信息,這個信息可以從JavaMail的javadocs文檔中的com.sun.mail.smtp包的幫助文檔中 ??? ??? ?* 看到*/ ??? ??? props.setProperty("mail.smtp.auth", "true"); ??? ??? Session session = Session.getInstance(props); ??? ??? session.setDebug(true); ??? ??? return session; ??? } ??? /** ??? ?* create MimeMessage,used the MultiBodyPart and MimeBodyPart ??? ?* @param session ??? ?* @return ??? ?* @throws Exception ??? ?*/ ??? public MimeMessage createMessage(Session session) throws Exception { ??? ??? MimeMessage message = new MimeMessage(session); ??? ??? message.setFrom(new InternetAddress(from)); ??? ??? message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); ??? ??? message.setSubject(subject); ??? ??? ??? ??? MimeMultipart multiPart = new MimeMultipart("related"); ??? ??? ??? ??? MimeBodyPart htmlBodyPart = new MimeBodyPart(); ??? ??? htmlBodyPart.setContent(body,"text/html;charset = GBK"); ??? ??? multiPart.addBodyPart(htmlBodyPart); ??? ??? ??? ??? MimeBodyPart gifBodyPart = new MimeBodyPart(); ??? ??? FileDataSource fds = new FileDataSource("d://zzz//love.jpg"); ??? ??? gifBodyPart.setDataHandler(new DataHandler(fds)); ??? ??? gifBodyPart.setContentID("love_jpg"); ??? ??? multiPart.addBodyPart(gifBodyPart); ??? ??? message.setContent(multiPart); ??? ??? message.saveChanges(); ??? ??? return message; ??? } ??? public static void main(String[] args) throws Exception { ??? ??? String server = "smtp.sina.com.cn"; ??? ??? String user = "15829004147@sina.cn"; ??? ??? String pass = "XXX";//密碼 ??? ??? ??? ??? HtmlMessageSender sender = new HtmlMessageSender(); ??? ??? Session session = sender.createSession(); ??? ??? MimeMessage message = sender.createMessage(session); ??? ??? ??? ??? //獲取Transport對象,并連接郵件服務器發送郵件 ??? ??? Transport transport =? session.getTransport(); ??? ??? transport.connect(server, user, pass); ??? ??? transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); ??? ??? transport.close(); ??? ??? ??? } ??? ??? ??? ??? ??? }