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

使用javamail API发送带有附件的电子邮件,java,email,datasource,jakarta-mail,transport,Java,Email,Datasource,Jakarta Mail,Transport,我正在尝试发送一封带有Java附件文件的电子邮件 当我发送没有附件的电子邮件时,我会收到电子邮件,但当我添加附件时,我不会收到任何东西,也不会收到任何错误消息 这是我正在使用的代码: public void send () throws AddressException, MessagingException{ //system properties Properties props = new Properties(); props.put("mail.smtp.localhost

我正在尝试发送一封带有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();
    } 
 }
如何更正此问题?

有关详细信息,请参阅JavaMail常见问题解答。特别是,协议跟踪将告诉您更多关于每种情况下发生的情况。当你在那里的时候,你也会发现使用GMail的技巧


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

您可以尝试以下操作:

File f = new File(file);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(f);
multipart.addBodyPart(attachmentPart);
请参阅以下方面的更多详细信息:

  • 禁用你的防病毒软件
  • 因为你有这样的警告

    请尝试此代码。。。它帮助你

    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);
            }
        }
    }
    

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

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

    如果您想通过访问本地目录通过gmail发送附件,那么您需要按照下面程序中的指示使用要设置为DataSource构造函数类的File对象。这将避免“拒绝访问”异常

    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);
            }
        }
    }
    

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

    标题部分将包含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);
    
    有关更多信息,请参阅此链接