java 發送郵件帶附件,正文帶圖片


 

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;
import javax.mail.internet.MimeUtility;

public class SendEmail
{
//收件人郵箱地址
private String[] to;
//抄送人郵箱地址
private String[] copyto;
//發件人郵箱地址
private String from ="xxx";
//SMTP服務器地址 如:smtp.163.com
private String smtpServer = "xxx";
//登錄SMTP服務器的用戶名(不需要后面帶@xxx.com)
private String username ="";
//登錄SMTP服務器的密碼 (服務密碼,不是登錄密碼)
private String password ="xxx";
//郵件主題
private String subject;
//郵件正文
private String content;
//記錄所有附件文件的集合
List<String> attachments = new ArrayList<String>();
// 發件人昵稱 
private String senderNick = "xxx";
//無參數的構造器
public SendEmail()
{
}

public SendEmail(String[] to , String from , String smtpServer
, String username , String password
, String subject , String content,String senderNick,String[] copyto)
{
this.to = to;
this.from = from;
this.smtpServer = smtpServer;
this.username = username;
this.password = password;
this.subject = subject;
this.content = content;
this.senderNick = senderNick;
this.copyto = copyto;
}
//to屬性的setter方法
public void setTo(String[] to)
{
this.to = to;
}
//to屬性的setter方法
public void setCopyto(String[] copyto)
{
this.copyto = copyto;
}
//from屬性的setter方法
public void setFrom(String from)
{
this.from = from;
}
//smtpServer屬性的setter方法
public void setSmtpServer(String smtpServer)
{
this.smtpServer = smtpServer;
}
//username屬性的setter方法
public void setUsername(String username)
{
this.username = username;
}
//password屬性的setter方法
public void setPassword(String password)
{
this.password = password;
}
//subject屬性的setter方法
public void setSubject(String subject)
{
this.subject = subject;
}
//content屬性的setter方法
public void setContent(String content)
{
this.content = content;
}

public void setSenderNick(String senderNick)
{
this.senderNick = senderNick;
}

//把郵件主題轉換為中文
public String transferChinese(String strText)
{
try
{
strText = MimeUtility.encodeText(new String(strText.getBytes() , "UTF-8"), "UTF-8", null);
}
catch(Exception e)
{
e.printStackTrace();
}
return strText;
}
//增加附件,將附件文件名添加的List集合中
public void attachfile(String fname)
{
attachments.add(fname);
}
//發送郵件
public boolean send(String path1,String path2) throws MalformedURLException
{
//創建郵件Session所需的Properties對象
Properties props = new Properties();
props.put("mail.smtp.host" , smtpServer);
props.put("mail.smtp.auth" , "true");
props.put("mail.smtp.debug" , "true");
//創建Session對象
Session session = Session.getDefaultInstance(props
//以匿名內部類的形式創建登錄服務器的認證對象
, new Authenticator()
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
//構造MimeMessage並設置相關屬性值
MimeMessage msg = new MimeMessage(session);

String nick = "";
try {
nick = javax.mail.internet.MimeUtility.encodeText(senderNick);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
//設置發件人
try {
msg.setFrom(new InternetAddress(from,nick));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
//設置收件人
if (to != null && to.length > 0) {
String toListStr = getMailList(to);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toListStr));
}

//設置抄送人
if (copyto != null && copyto.length > 0) {
String copytoListStr = getMailList(copyto);
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copytoListStr));
}
//InternetAddress[] addresses = {new InternetAddress(toListStr)};
//msg.setRecipients(Message.RecipientType.TO , addresses);
//設置郵件主題
subject = transferChinese(subject);
msg.setSubject(subject);
//構造Multipart
Multipart mp = new MimeMultipart();
//向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setContent(content, "text/html;charset=UTF-8");
//將BodyPart添加到MultiPart中
mp.addBodyPart(mbpContent);

//path1="D:\\xxx.png";
mbpContent = new MimeBodyPart();
DataSource fd = new FileDataSource(path1);
mbpContent.setDataHandler(new DataHandler(fd));
mbpContent.setHeader("Content-ID", "<image1>");
mp.addBodyPart(mbpContent);

//path2="D:\\xxx.png";
mbpContent = new MimeBodyPart();
DataSource fd2 = new FileDataSource(path2);
mbpContent.setDataHandler(new DataHandler(fd2));
mbpContent.setHeader("Content-ID", "<image2>");
mp.addBodyPart(mbpContent);

//向Multipart添加附件
//遍歷附件列表,將所有文件添加到郵件消息里
for(String efile : attachments)
{
MimeBodyPart mbpFile = new MimeBodyPart();
//以文件名創建FileDataSource對象
FileDataSource fds = new FileDataSource(efile);
//處理附件
mbpFile.setDataHandler(new DataHandler(fds));
try {
mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//將BodyPart添加到MultiPart中
mp.addBodyPart(mbpFile);
}

//清空附件列表
attachments.clear();
//向Multipart添加MimeMessage
msg.setContent(mp);
//設置發送日期
msg.setSentDate(new Date());
//發送郵件
Transport.send(msg);
}
catch (MessagingException mex)
{
mex.printStackTrace();
return false;
}
return true;
}


//多用戶發送用,號格開
public String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}

}
}
return toList.toString();
}



public static void main(String[] args)
{

SendEmail sendMail = new SendEmail();
//設置收件人的地址多人用逗號隔開
String[] to = {"xxxx@xx.com", "xxx@xxxx.com"};
sendMail.setTo(to);
//設置抄送人人的地址多人用逗號隔開
String[] copyto = {"xxxx@xx.com"};
sendMail.setCopyto(copyto);

//設置標題
sendMail.setSubject("測試郵件標題!");
//設置內容
StringBuffer sb = new StringBuffer();
sb.append("<body>" );
sb.append("<p style='text-align:left'>hi,all</p>")
.append("<p style='text-align:left;text-indent:2em;'>這里是測試數據!</p>");

sendMail.setContent(sb.toString());
//附件
sendMail.attachfile("D://xxx.xls");
try {

//可以在這里設置你要發送的圖片路徑
if (sendMail.send(null,null))
{
System.out.println("---郵件發送成功---");
}
} catch (MalformedURLException e) {

e.printStackTrace();
}

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM