怎么用java发送带附件的邮件代码详解

Python012

怎么用java发送带附件的邮件代码详解,第1张

package email  

import java.io.BufferedReader   

import java.io.File  

import java.io.FileInputStream  

import java.io.FileNotFoundException  

import java.io.IOException  

import java.io.InputStream  

import java.io.InputStreamReader  

import java.io.PrintWriter  

import java.io.UnsupportedEncodingException  

import java.net.Socket  

import java.nio.charset.Charset  

import java.text.SimpleDateFormat  

import java.util.ArrayList  

import java.util.Date  

import java.util.HashMap  

import java.util.List  

import java.util.Map  

import sun.misc.BASE64Encoder  

public class Mail {  

private static final String LINE_END = "\r\n"  

private boolean isDebug = true  

private boolean isAllowReadSocketInfo = true  

private String host  

private String from  

private List<String> to  

private List<String> cc  

private List<String> bcc  

private String subject  

private String user  

private String password  

private String contentType  

private String boundary  

private String boundaryNextPart  

private String contentTransferEncoding  

private String charset  

private String contentDisposition  

private String content  

private String simpleDatePattern  

private String defaultAttachmentContentType  

private List<MailPart> partSet  

private static Map<String, String> contentTypeMap  

static {  

// MIME Media Types  

contentTypeMap = new HashMap<String, String>()  

contentTypeMap.put("xls", "application/vnd.ms-excel")  

contentTypeMap.put("xlsx", "application/vnd.ms-excel")  

contentTypeMap.put("xlsm", "application/vnd.ms-excel")  

contentTypeMap.put("xlsb", "application/vnd.ms-excel")  

contentTypeMap.put("doc", "application/msword")  

contentTypeMap.put("dot", "application/msword")  

contentTypeMap.put("docx", "application/msword")  

contentTypeMap.put("docm", "application/msword")  

contentTypeMap.put("dotm", "application/msword")  

}  

private class MailPart extends Mail {  

public MailPart() {  

}  

}  

public Mail() {  

defaultAttachmentContentType = "application/octet-stream"  

simpleDatePattern = "yyyy-MM-dd HH:mm:ss"  

boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis()  

boundaryNextPart = "--" + boundary  

contentTransferEncoding = "base64"  

contentType = "multipart/alternative"  

charset = Charset.defaultCharset().name()  

partSet = new ArrayList<MailPart>()  

to = new ArrayList<String>()  

cc = new ArrayList<String>()  

bcc = new ArrayList<String>()  

}  

private String getPartContentType(String fileName) {  

String ret = null  

if (null != fileName) {  

int flag = fileName.lastIndexOf(".")  

if (0 <= flag && flag < fileName.length() - 1) {  

fileName = fileName.substring(flag + 1)  

}  

ret = contentTypeMap.get(fileName)  

}  

if (null == ret) {  

ret = defaultAttachmentContentType  

}  

return ret  

}  

private String toBase64(String str, String charset) {  

if (null != str) {  

try {  

return toBase64(str.getBytes(charset))  

} catch (UnsupportedEncodingException e) {  

e.printStackTrace()  

}  

}  

return ""  

}  

private String toBase64(byte[] bs) {  

return new BASE64Encoder().encode(bs)  

}  

private String toBase64(String str) {  

return toBase64(str, Charset.defaultCharset().name())  

}  

private String getAllParts() {  

int partCount = partSet.size()  

StringBuilder sbd = new StringBuilder(LINE_END)  

for (int i = partCount - 1 i >= 0 i--) {  

Mail attachment = partSet.get(i)  

String attachmentContent = attachment.getContent()  

if (null != attachmentContent && 0 < attachmentContent.length()) {  

sbd.append(getBoundaryNextPart()).append(LINE_END)  

sbd.append("Content-Type: ")  

sbd.append(attachment.getContentType())  

sbd.append(LINE_END)  

sbd.append("Content-Transfer-Encoding: ")  

sbd.append(attachment.getContentTransferEncoding())  

sbd.append(LINE_END)  

if (i != partCount - 1) {  

sbd.append("Content-Disposition: ")  

sbd.append(attachment.getContentDisposition())  

sbd.append(LINE_END)  

}  

sbd.append(LINE_END)  

sbd.append(attachment.getContent())  

sbd.append(LINE_END)  

}  

}  

sbd.append(LINE_END)  

sbd.append(LINE_END)  

partSet.clear()  

return sbd.toString()  

}  

private void addContent() {  

if (null != content) {  

MailPart part = new MailPart()  

part.setContent(toBase64(content))  

part.setContentType("text/plaincharset=\"" + charset + "\"")  

partSet.add(part)  

}  

}  

private String listToMailString(List<String> mailAddressList) {  

StringBuilder sbd = new StringBuilder()  

if (null != mailAddressList) {  

int listSize = mailAddressList.size()  

for (int i = 0 i < listSize i++) {  

if (0 != i) {  

sbd.append("")  

}  

sbd.append("<").append(mailAddressList.get(i)).append(">")  

}  

}  

return sbd.toString()  

}  

private List<String> getrecipient() {  

List<String> list = new ArrayList<String>()  

list.addAll(to)  

list.addAll(cc)  

list.addAll(bcc)  

return list  

}  

public void addAttachment(String filePath) {  

addAttachment(filePath, null)  

}  

public void addTo(String mailAddress) {  

this.to.add(mailAddress)  

}  

public void addCc(String mailAddress) {  

this.cc.add(mailAddress)  

}  

public void addBcc(String mailAddress) {  

this.bcc.add(mailAddress)  

}  

public void addAttachment(String filePath, String charset) {  

if (null != filePath && filePath.length() > 0) {  

File file = new File(filePath)  

try {  

addAttachment(file.getName(), new FileInputStream(file),  

charset)  

} catch (FileNotFoundException e) {  

System.out.println("错误:" + e.getMessage())  

System.exit(1)  

}  

}  

}

上传附件,实际上就是将文件存储到远程服务器,进行临时存储。举例:

**

* 上传文件

*

* @param fileName

* @param plainFilePath 文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null

ByteArrayOutputStream bos = null

FTPClient ftpClient = new FTPClient()

String bl = "false"

try {

fis = new FileInputStream(plainFilePath)

bos = new ByteArrayOutputStream(fis.available())

byte[] buffer = new byte[1024]

int count = 0

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count)

}

bos.flush()

Log.info("加密上传文件开始")

Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)

FTPFile[] fs

fs = ftpClient.listFiles()

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl="true"

ftpClient.changeWorkingDirectory("/"+filepath+"")

}

}

Log.info("检查文件路径是否存在:/"+filepath)

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath)

return bl

}

ftpClient.setBufferSize(1024)

ftpClient.setControlEncoding("GBK")

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)

ftpClient.storeFile(fileName, fis)

Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/")

return bl

} catch (Exception e) {

throw e

} finally {

if (fis != null) {

try {

fis.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (bos != null) {

try {

bos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

}

}

备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。

我们要用DOMINO5R的例子重写一下:

rti.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null,

attachFilePath, attachFilePath)// 添加附件

注:其中rti = (RichTextItem) memo.createRichTextItem("Body")

让邮件带上附件就一句话,很简单吧。

如果,你不明白其中的参数,还是会搞不出来,一个字晕!

其中前两个参数我就不说了,第三个和第四个参数写成一样就可以了。

强烈注意:

1* 添加的附件必须放在DOMINO服务器上,不能放在客户端添加附件,不要问为什么,这是事实。你在客户端的硬盘上无论放在哪,它也不让你上传。

2*我们的项目环境,DOMINO是运行在AS400上,它的安装目录是em_01,我们就假设把附件放在AS400 的em_01/test/test.tar,在程序使用相对路径,"test/test.tar"相对于邮件的根目录em_01.

如果,按我说的做法应该不会有问题了。若想看一个完整例子,请参考我的“java在收。发lotus邮件的实例了”。