9

我正在尝试用 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();
    } 
 }

我该如何纠正?

4

5 回答 5

16
  1. 禁用您的防病毒软件

因为你有这样的警告

警告消息表单防病毒

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

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);
        }
    }
}
于 2014-01-13T06:33:32.287 回答
1

有关调试技​​巧,请参阅 JavaMail FAQ 。特别是,协议跟踪将告诉您更多关于每种情况下发生的情况。当您在那里时,您还会发现使用 GMail 的提示。

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

于 2013-06-18T18:31:16.407 回答
1

You can try something like:

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

See more details on: Send email via SMTP with attachment, plain/text, and text/hml

于 2013-06-22T04:03:45.810 回答
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);
        }
    }
}
于 2015-09-15T04:57:41.523 回答
0

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

标题部分将包含 from、to 和 subject。

正文包含附件。为了支持在体内携带附件,类型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

于 2018-06-23T01:48:50.153 回答