Java 发送邮件

依赖包是:
javamail-1.4.3



// Sender, Recipient, CCRecipient, and BccRecipient are comma-separated
// lists of addresses. Body can span multiple CR/LF-separated lines.
// Attachments is a ///-separated list of file names.
// template path "/usr/tmp/attachments";

// 给用户发送多附件
public static String Send(String _userName, String _password, String SMTPServer, String Sender, String Recipient, String CcRecipient,
String BccRecipient, String Subject, String Body, String attachmentLists) {
// Error status;
String ErrorStatus = null;
Properties props = System.getProperties();
props.put("mail.smtp.host", SMTPServer);
props.put("mail.smtp.auth", "true");
final String userName = _userName;
final String password = _password;
// Session session = Session.getDefaultInstance(props, null);
Session session = null;
if (password == null) {
session = Session.getDefaultInstance(props, null);
} else {
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
}

try {
// Create a message.
MimeMessage msg = new MimeMessage(session);
// extracts the senders and adds them to the message.
// Sender is a comma-separated list of e-mail addresses as per
// RFC822.
{
InternetAddress[] TheAddresses = InternetAddress.parse(Sender);
msg.addFrom(TheAddresses);

}
// Extract the recipients and assign them to the message.
// Recipient is a comma-separated list of e-mail addresses as per
// RFC822.
{
InternetAddress[] TheAddresses = InternetAddress.parse(Recipient);
msg.addRecipients(Message.RecipientType.TO, TheAddresses);
}
// Extract the Cc-recipients and assign them to the message;
// CcRecipient is a comma-separated list of e-mail addresses as per
// RFC822
if (null != CcRecipient) {
InternetAddress[] TheAddresses = InternetAddress.parse(CcRecipient);
msg.addRecipients(Message.RecipientType.CC, TheAddresses);
}
// Extract the Bcc-recipients and assign them to the message;
// BccRecipient is a comma-separated list of e-mail addresses as per
// RFC822
if (null != BccRecipient) {
InternetAddress[] TheAddresses = InternetAddress.parse(BccRecipient);
msg.addRecipients(Message.RecipientType.BCC, TheAddresses);
}
// Subject field
msg.setSubject(Subject);
// Create the Multipart to be added the parts to
Multipart mp = new MimeMultipart();
// Create and fill the first message part
{
MimeBodyPart mbp = new MimeBodyPart();
// mbp.setText(Body);
mbp.setContent(Body, "text/html; charset=utf-8");
// Attach the part to the multipart;
mp.addBodyPart(mbp);
}

if (null != attachmentLists && !"".equals(attachmentLists)) {
// 如何发送单个附件路径为空 则选择发送多个附件
int StartIndex = 0, PosIndex = 0;
while (-1 != (PosIndex = attachmentLists.indexOf(",", StartIndex))) {
// Create and fill other message parts;
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attachmentLists.substring(StartIndex, PosIndex));
mbp.setDataHandler(new DataHandler(fds));

sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";

mbp.setFileName(fileName);
mp.addBodyPart(mbp);
PosIndex += 1;
StartIndex = PosIndex;
}
// Last, or only, attachment file;
if (StartIndex < attachmentLists.length()) {
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attachmentLists.substring(StartIndex));
mbp.setDataHandler(new DataHandler(fds));

sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";

mbp.setFileName(fileName);
mp.addBodyPart(mbp);
}

}

// Add the Multipart to the message
msg.setContent(mp);
// Set the Date: header
msg.setSentDate(new Date());
// Send the message;
try {
Transport.send(msg);

} catch (Throwable cause) {
Throwable ex = new Throwable();
StackTraceElement[] stackElements = ex.getStackTrace();
StringBuffer sb = new StringBuffer();
if (stackElements != null) {
for (int i = 0; i < stackElements.length; i++) {
sb.append(stackElements[i].getClassName() + "\n");
sb.append(stackElements[i].getFileName() + "\n");
sb.append(stackElements[i].getLineNumber() + "\n");
sb.append(stackElements[i].getMethodName() + "\n");
sb.append("-----------------------------------" + "\n");
}
}
System.out.println(sb.toString());
ErrorStatus += sb.toString() + cause.fillInStackTrace();
}

} catch (MessagingException MsgException) {
// ErrorMessage = MsgException.toString();
Exception TheException = null;
if ((TheException = MsgException.getNextException()) != null)
// ErrorMessage = ErrorMessage + "\n" + TheException.toString();
ErrorStatus = "Exception:" + TheException.toString();
}
return ErrorStatus;
} // End Send Class


sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";


此处注意需要给文件名字编码 否则容易出现乱码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值