?? mailsender.java
字號:
for (int i = 0; i < arrayList1.size(); i++) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource((String) arrayList1.get(i));
messageBodyPart.setDataHandler(new DataHandler(source));
String contentId = "<" + (String) arrayList2.get(i) + ">";
messageBodyPart.setHeader("Content-ID", contentId);
messageBodyPart.setFileName((String) arrayList1.get(i));
multipart.addBodyPart(messageBodyPart);
}
}
//處理要發送的html文件,主要是針對html文件中的圖片
private String getContent(String mailContent) {
try {
Parser parser = new Parser();
parser.setInputHTML(new String(mailContent.getBytes(), ISO8859_1));
//Parser parser = Parser.createParser(new String(mailContent.getBytes(), ISO8859_1));
Node[] images = parser.extractAllNodesThatMatch(HtmlNodeFilters.imageFilter).toNodeArray();
for(int i=0;i<images.length;i++) {
ImageTag imgTag = (ImageTag) images[i];
if(!imgTag.getImageURL().toLowerCase().startsWith("http://"))
arrayList1.add(imgTag.getImageURL());
}
} catch (UnsupportedEncodingException e1) {
} catch (ParserException e) {}
String afterReplaceStr = mailContent;
//在html文件中用"cid:"+Content-ID來替換原來的圖片鏈接
for (int m = 0; m < arrayList1.size(); m++) {
arrayList2.add(createRandomStr());
String addString = "cid:" + (String) arrayList2.get(m);
afterReplaceStr = mailContent.replaceAll(
(String) arrayList1.get(m), addString);
}
return afterReplaceStr;
}
//產生一個隨機字符串,為了給圖片設定Content-ID值
private String createRandomStr() {
char[] randomChar = new char[8];
for (int i = 0; i < 8; i++) {
randomChar[i] = (char) (Math.random() * 26 + 'a');
}
String replaceStr = new String(randomChar);
return replaceStr;
}
private final static String CONTENT_TYPE = "text/html;charset=GB2312";
private final static String ISO8859_1 = "8859_1";
};
}
/**
* 用于實現郵件發送用戶驗證
* @see javax.mail.Authenticator#getPasswordAuthentication
*/
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, userpasswd);
}
/**
* 設置郵件標題
* @param mailSubject
* @throws MessagingException
*/
public void setSubject(String mailSubject) throws MessagingException {
mailMessage.setSubject(mailSubject);
}
/**
* 所有子類都需要實現的抽象方法,為了支持不同的郵件類型
* @param mailContent
* @throws MessagingException
*/
public abstract void setMailContent(String mailContent) throws MessagingException;
/**
* 設置郵件發送日期
* @param sendDate
* @throws MessagingException
*/
public void setSendDate(Date sendDate) throws MessagingException {
mailMessage.setSentDate(sendDate);
}
/**
* 設置郵件發送附件
* @param attachmentName
* @throws MessagingException
*/
public void setAttachments(String attachmentName) throws MessagingException {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentName);
messageBodyPart.setDataHandler(new DataHandler(source));
int index = attachmentName.lastIndexOf(File.separator);
String attachmentRealName = attachmentName.substring(index + 1);
messageBodyPart.setFileName(attachmentRealName);
multipart.addBodyPart(messageBodyPart);
}
/**
* 設置發件人地址
* @param mailFrom
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void setMailFrom(String mailFrom, String sender) throws UnsupportedEncodingException, MessagingException {
if(sender!=null)
mailMessage.setFrom(new InternetAddress(mailFrom, sender));
else
mailMessage.setFrom(new InternetAddress(mailFrom));
}
/**
* 設置收件人地址,收件人類型為to,cc,bcc(大小寫不限)
* @param mailTo 郵件接收者地址
* @param mailType 值為to,cc,bcc
* @author Liudong
*/
public void setMailTo(String[] mailTo, String mailType) throws Exception {
for (int i = 0; i < mailTo.length; i++) {
mailToAddress = new InternetAddress(mailTo[i]);
if (mailType.equalsIgnoreCase("to")) {
mailMessage.addRecipient(Message.RecipientType.TO,mailToAddress);
} else if (mailType.equalsIgnoreCase("cc")) {
mailMessage.addRecipient(Message.RecipientType.CC,mailToAddress);
} else if (mailType.equalsIgnoreCase("bcc")) {
mailMessage.addRecipient(Message.RecipientType.BCC,mailToAddress);
} else {
throw new Exception("Unknown mailType: " + mailType + "!");
}
}
}
/**
* 開始發送郵件
* @throws MessagingException
* @throws SendFailedException
*/
public void sendMail() throws MessagingException, SendFailedException {
if (mailToAddress == null)
throw new MessagingException("The recipient is required.");
mailMessage.setContent(multipart);
Transport.send(mailMessage);
}
public MimeMessage getMimeMessage() throws MessagingException{
if (mailToAddress == null)
throw new MessagingException("The recipient is required.");
mailMessage.setContent(multipart);
return mailMessage;
}
/**
* 郵件發送測試
* @param args
*/
public static void main(String args[]) {
String mailHost = "smtp.163.com"; //發送郵件服務器地址
String mailUser = "user1"; //發送郵件服務器的用戶帳號
String mailPassword = "password1"; //發送郵件服務器的用戶密碼
String[] toAddress = {"user1@163.com"};
//使用超文本格式發送郵件
MailSender sendmail = MailSender.getHtmlMailSender(mailHost, mailUser,mailPassword);
//使用純文本格式發送郵件
//MailSender sendmail = MailSender.getTextMailSender(mailHost, mailUser,mailPassword);
try {
sendmail.setSubject("郵件發送測試");
sendmail.setSendDate(new Date());
String content = "<H1>你好,中國</H1><img src=\"http://www.javayou.com/images/logo.gif\">";
//請注意如果是本地圖片比如使用斜杠作為目錄分隔符,如下所示
content+="<img src=\"D:/EclipseM7/workspace/JDlog/dlog/images/rss200.png\"/>";
sendmail.setMailContent(content); //
sendmail.setAttachments("E:\\TOOLS\\pm_sn.txt");
sendmail.setMailFrom("user1@163.com","發送者");
sendmail.setMailTo(toAddress, "to");
//sendmail.setMailTo(toAddress, "cc");//設置抄送給...
//開始發送郵件
System.out.println("正在發送郵件,請稍候.......");
sendmail.sendMail();
System.out.println("恭喜你,郵件已經成功發送!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -