2 o19830015 o19830015 于 2012.11.26 17:09 提问

编码实现gmail中的附件

android问题:

我的代码已经实现了用gmail发送邮件,现在我需要发送的邮件可以添加附件,没有用户交互。谁能帮忙告诉一下怎么实现啊?

1个回答

Kill_it
Kill_it   2012.11.26 17:24
已采纳

直接把代码给你吧

public synchronized void sendMail(String subject, String body, String sender, String recipients, File attachment) throws Exception {
    try{
    MimeMessage message = new MimeMessage(session);
    message.setSender(new InternetAddress(sender));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(body);

    MimeBodyPart mbp2 = new MimeBodyPart();
    FileDataSource fds = new FileDataSource(attachment);
    mbp2.setDataHandler(new DataHandler(fds));
    mbp2.setFileName(fds.getName());

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);

    message.setContent(mp);

    if (recipients.indexOf(',') > 0)
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
    else
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
    Transport.send(message);
    }catch(Exception e){

    }
}
o19830015
o19830015 O谢谢
大约 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!