啥也不說了,直接放代碼,一切盡在代碼中。。。
1、
要發送的郵件數據對象:
public class MailData
{
/** 發件人的用戶名。 */
private String userName;
/** 發件的密碼。 */
private String password;
/** 發件人的郵件地址 */
private String mailAddress;
/** 收件人的地址列表。 */
private String[] receiveAddress;
/** 發送的pop郵箱服務器地址。 */
private String smtp;
/** 郵件主題。 */
private String subject;
/** 郵件正文。 */
private String content;
/** 郵件正文是否是純文本。 */
private boolean isHtml;
private File[] files;
// get/set方法...
}
public class MailSend
{
/**
* 發送郵件。
*
* @param data
* 郵件內容對象。
* @throws Exception
*/
public void sendMail(final MailData data) throws Exception
{
Session session = this.getSession(data);
Message msg = new MimeMessage(session);
this.setMailMsg(msg, data);
Transport.send(msg);
}
/**
* 設置郵件信息。包括郵件內容、標題、發送者、接收者、附件等信息。
*
* @param msg
* Message對象。
* @param data
* 郵件信息內容。
* @throws Exception
*/
private void setMailMsg(Message msg, MailData data) throws Exception
{
// 設置郵件接收者。
msg.addRecipients(Message.RecipientType.TO, Utils.toAddress(data.getReceiveAddresses()));
// 設置郵件發送者。
msg.setFrom(Utils.toAddress(data.getSendAddress()));
// 設置郵件的標題。這裏最好使用setHeader的方式,使用setSubject的方式無法指定編碼格式,其它語言可能會亂碼。
// 如果這裏的標題太長了的話,始終會有一部分會是亂碼。這點還不知道如何修改。
msg.setHeader("Subject", MimeUtility.encodeText(data.getSubject(), "utf-8", "B"));
// msg.setSubject(data.getSubject());
Multipart multipart = new MimeMultipart();
this.setMailContentPart(data, multipart);
msg.setContent(multipart);
}
/**
* 設置郵件正文和附件。
*
* @param data
* 郵件的信息內容。
* @param multipart
* 郵件的對象。
*/
private void setMailContentPart(MailData data, Multipart multipart) throws Exception
{
// 設置郵件內容。
MimeBodyPart bPart = new MimeBodyPart();
if (data.isHtml())
{
bPart.setContent(data.getContent(), "text/html;charset=UTF-8");
}
else
{
// 以text設置時要設置編碼方式,最好爲utf-8,不然其它語言可能亂碼。
bPart.setText(data.getContent(), "utf8");
}
multipart.addBodyPart(bPart);
// 設置郵件附件。
if (data.getFiles() != null)
{
for (File f : data.getFiles())
{
if ((f != null) && f.isFile())
{
bPart = new MimeBodyPart();
DataSource source = new FileDataSource(f);
bPart.setDataHandler(new DataHandler(source));
// 設置文件名時要設置編碼,不然會亂碼的。最好指定編碼格式爲utf8
bPart.setFileName(MimeUtility.encodeText(f.getName(), "utf-8", "B"));
multipart.addBodyPart(bPart);
}
}
}
}
/**
* 根據郵件的服務器信息獲取Session對象。
*
* @param data
* 郵件的服務器信息對象。
* @return 返回獲取的Session對象。
*/
private Session getSession(final MailData data)
{
Properties pro = new Properties();
// 設置郵件發送smtp服務器。
pro.put("mail.smtp.host", data.getSmtp());
// 設置發送郵件需要驗證身份
pro.put("mail.smtp.auth", "true");
// 發送郵件的身份認證對象。
Authenticator auth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(data.getUserName(), data.getPassword());
}
};
return Session.getDefaultInstance(pro, auth);
}
}