使用javamail API发送带附件的电子邮件

时间:2013-06-17 20:46:32

标签: java email datasource javamail transport

我正在尝试使用Java发送带有附件的电子邮件。

当我发送没有附件的电子邮件时,我收到了电子邮件,但是当我添加附件时,我没有收到任何内容,而且我没有收到任何错误消息。

这是我正在使用的代码:

public void send () throws AddressException, MessagingException{
    //system properties

Properties  props = new Properties();
props.put("mail.smtp.localhost", "localhost"); 
props.put("mail.smtp.host",Configurations.getInstance().email_serverIp); 


/*
 *  create some properties and get the default Session
 */
session = Session.getDefaultInstance(props, null);

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

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("zouhaier.mhamdi@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("zouhaier.mhamdi@gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");

MimeBodyPart messageBodyPart = new MimeBodyPart();

Multipart multipart = new MimeMultipart();
   generateCsvFile("/tmp/test.csv"); 
messageBodyPart = new MimeBodyPart();
String file = "/tmp/test.csv";
String fileName = "test.csv"; 
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);

message.setContent(multipart);

System.out.println("Sending");

Transport.send(message);

System.out.println("Done");

}

private static void generateCsvFile(String sFileName)
{
    try
    {

    FileWriter writer = new FileWriter(sFileName);

    writer.append("DisplayName");
    writer.append(',');
    writer.append("Age");
    writer.append(',');
    writer.append("YOUR NAME");
    writer.append(',');

    writer.append('\n');
    writer.append("Zou");
    writer.append(',');
    writer.append("26");
    writer.append(',');
    writer.append("zouhaier");


    //generate whatever data you want

    writer.flush();
    writer.close();
    }
    catch(IOException e)
    {
         e.printStackTrace();
    } 
 }

我该如何纠正?

5 个答案:

答案 0 :(得分:14)

  1. 禁用您的反病毒
  2. 因为你有这样的警告

    warning message form antivirus

    试试这段代码......它可以帮助你......

    public class SendMail {
        public SendMail() throws MessagingException {
            String host = "smtp.gmail.com";
            String Password = "............";
            String from = "XXXXXXXXXX@gmail.com";
            String toAddress = "YYYYYYYYYYYYY@gmail.com";
            String filename = "C:/SendAttachment.java";
            // Get system properties
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtps.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            Session session = Session.getInstance(props, null);
    
            MimeMessage message = new MimeMessage(session);
    
            message.setFrom(new InternetAddress(from));
    
            message.setRecipients(Message.RecipientType.TO, toAddress);
    
            message.setSubject("JavaMail Attachment");
    
            BodyPart messageBodyPart = new MimeBodyPart();
    
            messageBodyPart.setText("Here's the file");
    
            Multipart multipart = new MimeMultipart();
    
            multipart.addBodyPart(messageBodyPart);
    
            messageBodyPart = new MimeBodyPart();
    
            DataSource source = new FileDataSource(filename);
    
            messageBodyPart.setDataHandler(new DataHandler(source));
    
            messageBodyPart.setFileName(filename);
    
            multipart.addBodyPart(messageBodyPart);
    
            message.setContent(multipart);
    
            try {
                Transport tr = session.getTransport("smtps");
                tr.connect(host, from, Password);
                tr.sendMessage(message, message.getAllRecipients());
                System.out.println("Mail Sent Successfully");
                tr.close();
    
            } catch (SendFailedException sfe) {
    
                System.out.println(sfe);
            }
        }
        public static void main(String args[]){
            try {
                SendMail sm = new SendMail();
            } catch (MessagingException ex) {
                Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

答案 1 :(得分:1)

请参阅debugging tips的JavaMail常见问题解答。特别是,协议跟踪将告诉您更多关于每种情况下发生的情况。当你在那里时,你会发现使用GMail的提示。

如果唯一的区别只是添加附件,那么它似乎不太可能是身份验证问题。您可能会收到一个您没有注意到的异常,因为您的send方法被声明为抛出MessagingException。

答案 2 :(得分:1)

您可以尝试以下内容:

File f = new File(file);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(f);
multipart.addBodyPart(attachmentPart);

详情请见Send email via SMTP with attachment, plain/text, and text/hml

答案 3 :(得分:1)

您可以使用用户名和密码访问Gmail。但gmail帐户将拒绝访问。

因此,您必须通过转到帐户设置,密码部分并取消验证代码安全设置或降低安全级别来更改安全级别,具体取决于旧的或最新的Gmail应用程序。

如果要通过访问本地目录通过gmail发送附件,则需要按照以下程序中的指示将File对象设置为DataSource构造函数类。这将避免“拒绝访问”例外。

import java.io.File;    
import java.io.IOException;    
import java.util.Properties;   
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailApp {
    public static void main(String[] args)throws IOException {
        final String username = "mygmail@gmail.com";
        final String password = "mypassword";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("dharmendrasundar@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("dharmendrasundar@gmail.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
            message.setSubject("Testing Subject");
            message.setText("PFA");

            MimeBodyPart messageBodyPart = new MimeBodyPart();
            Multipart multipart = new MimeMultipart();
            messageBodyPart = new MimeBodyPart();

            String attachmentPath = "C:/TLS/logs/26-Mar-2015";
            String attachmentName = "LogResults.txt";

            File att = new File(new File(attachmentPath), attachmentName);
            messageBodyPart.attachFile(att);

            DataSource source = new FileDataSource(att);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachmentName);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            System.out.println("Sending");
            Transport.send(message);
            Transport.send(message);
            System.out.println("Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

答案 4 :(得分:0)

电子邮件由标题和正文段组成。

页眉部分将包含从,到和主题。

正文包含附件。为了支持在体内携带附件,应该存在类型Multipart

Multipart对象包含多个部分,其中每个部分都表示为BodyPart类型,其子类MimeBodyPart –可以将文件作为其内容。

要将附件添加到邮件正文MimeBodyPart类中,提供了一些便捷的方法。

// JavaMail 1.3
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = "D:/test.pdf";

DataSource source = new FileDataSource(attachFile);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(attachFile).getName());

multipart.addBodyPart(attachPart);


// JavaMail 1.4
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = "D:/test.pdf";
attachPart.attachFile(attachFile);
multipart.addBodyPart(attachPart);

有关更多信息,请参见此链接。

https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm