发一封带附件的mail,代码很简单,留个记录
package file;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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 SendMail {
private Message mimeMsg;
private Session session;
private Properties props;
public SendMail() {
initial();
}
public static void main(String[] args) {
SendMail mail = new SendMail();
String mailBody = mail.getMailBody();
String fileName = "E:\\02_STUDY\\linux&unix.rar";
if (!mail.setData("java mail", mailBody, "baopei@xxxx.com",
"baopei@xxxx.com", fileName)) {
return;
}
if (mail.sendOut() == false) {
return;
}
}
private void initial() {
if (props == null) {
props = System.getProperties();
}
try {
session = Session.getDefaultInstance(props, null);
mimeMsg = new MimeMessage(session);
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean sendOut() {
try {
Transport transport = session.getTransport("smtp");
transport.connect("mailhost", "baopei", "password");
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
} catch (Exception e) {
return false;
}
}
private String getMailBody() {
StringBuffer str = new StringBuffer();
str
.append("<body>"
+ "<form>"
+ "<table width=\"400\" border=\"1\" cellpadding=\"1\" cellspacing=\"1\" bgColor=#eaeaea align=\"center\">"
+ "<tr bgcolor=\"#666666\">"
+ "<td align=\"center\"><font color=\"#FFFFFF\"><b>province</b></font></td>"
+ "<td align=\"center\"><font color=\"#FFFFFF\"><b>last week number</b></font></td>"
+ "</tr>");
str.append("<tr>");
str.append("<th nowrap><div align=\"center\">" + "baopei" + "</th>");
str.append("</tr>");
str.append("</table></form></body>");
String mailbody = str.toString();
return mailbody;
}
private boolean setData(String subject, String mailBody, String toUser,
String fromUser, String fileName) {
try {
mimeMsg.setSubject(subject);
// 注意,mail的附件和mail的内容要分别new一个bp
BodyPart bp = new MimeBodyPart();
bp.setContent(
"<meta http-equiv=Content-Type content=text/html;charset=gb2312>"
+ mailBody, "text/html;charset=GB2312");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bp);
bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(fileName);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
multipart.addBodyPart(bp);
mimeMsg.setContent(multipart);
mimeMsg.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(toUser));
mimeMsg.setFrom(new InternetAddress(fromUser));
mimeMsg.saveChanges();
return true;
} catch (Exception e) {
return false;
}
}
}
快快乐乐、认认真真生活才是真。