JavaMail 发送附件的例子

Here is the code to send an attachment:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
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.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource 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 );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值