JAVAMail附件问题(解决就结贴)
近日才搞javamail 请教大家个问题,我看到都是用FileDataSource,就是能不能不写文件,直接将指定字符串当文本附件发送出去.请大家给点例子或者是提示
------解决方案--------------------/*
* 创建日期 2007-1-30
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
package mail;
import
java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import
javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import
javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author Administrator
* @param
*
* TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class SendMail
{
public static void main(String[] args)
{
String host = " ";
String from = "t@inspur.com ";
String to = "chensong@inspur.com ";
Properties props = new Properties();
props.put( "mail.smtp.host ", "mail.inspur.com ");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
try
{
InternetAddress address = new InternetAddress( "chensong@inspur.com ", "test ");
InternetAddress toAddress = new InternetAddress( "chensong@inspur.com ", "chensong ");
message.setContent( "test ", "text/plain ");
message.setSubject( "标题 ");
message.setFrom(address);
// message.addRecipient(Message.RecipientType.TO,
// new InternetAddress(to));
// Transport transport = session.getTransport( "smtp ");
// transport.connect( "mail.inspur.com ", "cs ", "11111111Qw ");
// transport.sendMessage(message, message.getAllRecipients());
// transport.close();
message.addRecipient(Message.RecipientType.TO,toAddress);
Transport.send(message);
System.out.println( "ok! ");
} catch (Unsupported
EncodingException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (
MessagingException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
------解决方案--------------------使用ByteArrayDataSource类型数据源
MimeBodyPart mbp = new MimeBodyPart();
byte[] bytes = "this is a test ".getBytes();
ByteArrayDataSource bads = new ByteArrayDataSource(bytes, "text/plain ");
mbp.setDataHandler(new DataHandler(bads));
mbp.setDescription(Part.ATTACHMENT);
mbp.setFileName( "test.txt ");