JavaMail 发送附件的例子 (转)

本文提供了一个使用JavaMail API发送带有附件电子邮件的示例代码。该示例演示了如何设置SMTP服务器属性、创建MIME消息、添加正文与附件,并最终发送邮件。
JavaMail 发送附件的例子 (转)[@more@]Here is the code to send an attachment:

import Java.util.Properties;
import javax. Mail.*;
import javax.mail.inte .NET.*;
import javax.activation.*;

public class AttachExample {
 public static void main (String args[])
 throws Exception {
 String host = args[0];
 String from = args[1];
 String to = args[2];
 String fileAttachment = args[3];

 // Get system properties
 Properties props = System.getProperties();

 // Setup mail server
 props.put("mail.smtp.host", host);

 // Get session
 Session session =
 Session.getInstance(props, null);

 // Define message
 MimeMessage message =
 new MimeMessage(session);
 message.setFrom(
 new InternetAddress(from));
 message.addRecipient(
 Message.RecipientType.TO,
 new InternetAddress(to));
 message.setSubject(
 "Hello JavaMail Attachment");

 // create the message part
 MimeBodyPart messageBodyPart =
 new MimeBodyPart();

 //fill message
 messageBodyPart.setText("Hi");

 Multipart multipart = new MimeMultipart();
 multipart.ad dbodyPart(messageBodyPart);

 // Part two is attachment
 messageBodyPart = new MimeBodyPart();
 Data source source =
 new FileDataSource(fileAttachment);
 messageBodyPart.setDataHandler(
 new DataHandler(source));
 messageBodyPart.setFileName(fileAttachment);
 multipart.addBodyPart(messageBodyPart);

 // Put parts in message
 message.setContent(multipart);

 // Send the message
 Transport.send( message );
 }
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10752043/viewspace-989059/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10752043/viewspace-989059/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值