使用 Java 发送邮件附件

Posted

技术标签:

【中文标题】使用 Java 发送邮件附件【英文标题】:Sending mail attachment using Java 【发布时间】:2013-04-13 14:22:49 【问题描述】:

我正在尝试使用 Java 和 Gmail 发送电子邮件。我已将我的文件存储在云中,并将这些存储的文件作为附件发送到我的电子邮件中。

它应该将这些文件添加到此邮件中,而不是这些文件的链接。

如何发送此类附件?

【问题讨论】:

您必须能够在您的代码中从云端下载文件。之后,只需附加它们 示例tutorialspoint.com/javamail_api/… 使用这个 API:sourceforge.net/projects/easymail4j 【参考方案1】:

工作代码,我用过Java Mail 1.4.7 jar

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;

public class MailProjectClass 

public static void main(String[] args) 

    final String username = "your.mail.id@gmail.com";
    final String password = "your.password";

    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("from.mail.id@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to.mail.id@gmail.com"));
        message.setSubject("Testing Subject");
        message.setText("PFA");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();
        
        String file = "path of file to be attached";
        String fileName = "attachmentName";
        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");

     catch (MessagingException e) 
        e.printStackTrace();
    
  

【讨论】:

引发连接超时异常 我用过你的课,但它给出了这样的错误,“530 5.7.0 必须先发出 STARTTLS 命令。pa5sm839428pdb.28 - gsmtp”@NINCOMPOOP 尝试添加这个:props.put("mail.smtp.EnableSSL.enable","true"); @NINCOMPOOP :我收到以下异常 javax.mail.SendFailedException:发送失败;嵌套异常是:类 javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587;嵌套异常是:java.net.ConnectException:连接超时:在 javax.mail.Transport.send(Transport.java:80) 在 sendMail.SendMail4 处连接 javax.mail.Transport.send0(Transport.java:218)。在 sendMail.sel.main(sel.java:10) 处执行(SendMail4.java:70) 工作了 7 年,后来大流行,非常感谢【参考方案2】:

由于未知原因,当我向我的 gmail 地址发送电子邮件时,接受的答案部分有效。我有附件,但没有邮件正文。

如果您想要附件和文本,请根据接受的答案尝试此操作:

    Properties props = new java.util.Properties();
    props.put("mail.smtp.host", "yourHost");
    props.put("mail.smtp.port", "yourHostPort");
    props.put("mail.smtp.auth", "true");             
    props.put("mail.smtp.starttls.enable", "true");


    // Session session = Session.getDefaultInstance(props, null);
    Session session = Session.getInstance(props,
              new javax.mail.Authenticator() 
                protected PasswordAuthentication getPasswordAuthentication() 
                    return new PasswordAuthentication("user", "password");
                
              );


    Message msg = new MimeMessage(session);
    try 
        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        msg.setSubject("your subject");

        Multipart multipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText("your text");

        MimeBodyPart attachmentBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"

        multipart.addBodyPart(textBodyPart);  // add the text part
        multipart.addBodyPart(attachmentBodyPart); // add the attachement part

        msg.setContent(multipart);


        Transport.send(msg);
     catch (MessagingException e) 
        LOGGER.log(Level.SEVERE,"Error while sending email",e);
    

更新:

如果您想以 html 格式的内容发送邮件,您必须这样做

    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setContent(content, "text/html");

所以基本上setText 用于原始文本,并将很好地显示在包括 gmail 在内的每个服务器电子邮件上,setContent 更多用于 html 模板,如果您的内容被格式化为 html,它可能也可以在 gmail 中使用

p>

【讨论】:

这个修改对我有用。我正确获取了附件,但没有收到任何电子邮件正文。使用与@amdev 完全相同的代码,我收到了带有正文和附件的电子邮件。谢谢! 同意以上评论,这应该是公认的答案!【参考方案3】:

使用 Spring 框架,您可以添加许多附件:

package com.mkyong.common;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMail

    private JavaMailSender mailSender;
    private SimpleMailMessage simpleMailMessage;

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) 
        this.simpleMailMessage = simpleMailMessage;
    

    public void setMailSender(JavaMailSender mailSender) 
        this.mailSender = mailSender;
    

    public void sendMail(String dear, String content) 

       MimeMessage message = mailSender.createMimeMessage();

       try
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());
        helper.setText(String.format(
            simpleMailMessage.getText(), dear, content));

        FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
        helper.addAttachment(file.getFilename(), file);

         catch (MessagingException e) 
        throw new MailParseException(e);
         
         mailSender.send(message);
         

要知道如何配置你的项目来处理这段代码,请完整阅读this tutorial。

【讨论】:

【参考方案4】:

这对我有用。

这里我假设我的附件是PDF 类型格式。

注释是为了清楚地理解它。

public class MailAttachmentTester 
    public static void main(String[] args) 
        // Recipient's email ID needs to be mentioned.
        String to = "test@gmail.com";
        // Sender's email ID needs to be mentioned
        String from = "tester@gmail.com";
        final String username = "tester@gmail.com";//change accordingly
        final String password = "test";//change accordingly
        // Assuming you are sending email through relay.jangosmtp.net
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        // Get the Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() 
                    protected PasswordAuthentication getPasswordAuthentication() 
                        return new PasswordAuthentication(username, password);
                    
                );
        try 
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);
            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));
            // Set To: header field of the header.
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            // Set Subject: header field
            message.setSubject("Attachment");
            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();
            // Now set the actual message
            messageBodyPart.setText("Please find the attachment below");
            // Create a multipar message
            Multipart multipart = new MimeMultipart();
            // Set text message part
            multipart.addBodyPart(messageBodyPart);
            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            String filename = "D:/test.PDF";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            // Send the complete message parts
            message.setContent(multipart);
            // Send message
            Transport.send(message);
            System.out.println("Email Sent Successfully !!");
         catch (MessagingException e) 
            throw new RuntimeException(e);
        
    

 

【讨论】:

【参考方案5】:

如果您允许,它也适用于多附件,这是 NINCOMPOOP 的第一个以上答案,只需稍作修改,如下所示:

DataSource source,source2,source3,source4, ...;  
source = new FileDataSource(myfile);  
messageBodyPart.setDataHandler(new DataHandler(source));  
messageBodyPart.setFileName(myfile);  
multipart.addBodyPart(messageBodyPart);  

source2 = new FileDataSource(myfile2);  
messageBodyPart.setDataHandler(new DataHandler(source2));  
messageBodyPart.setFileName(myfile2);  
multipart.addBodyPart(messageBodyPart);  

source3 = new FileDataSource(myfile3);  
messageBodyPart.setDataHandler(new DataHandler(source3));  
messageBodyPart.setFileName(myfile3);  
multipart.addBodyPart(messageBodyPart);  

source4 = new FileDataSource(myfile4);  
messageBodyPart.setDataHandler(new DataHandler(source4));  
messageBodyPart.setFileName(myfile4);  
multipart.addBodyPart(messageBodyPart);  

...

message.setContent(multipart);

【讨论】:

不要误导:此修改仅涉及附加附件。很明显,还需要插入额外的附件。我将上面的代码放在一个单独的 bean 中,并将客户端接口放在一个 jsp 文件中,例如 ""

> ""

【参考方案6】:

为了发送 html 文件,我在项目中使用了以下代码。

final String userID = "usermail@gmail.com";
final String userPass = "userpass";
final String emailTo = "mailto@gmail.com"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() 
            protected PasswordAuthentication getPasswordAuthentication() 
                return new PasswordAuthentication(userID, userPass);
            
        );
try 

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

 catch (MessagingException e) 
    e.printStackTrace();




private static void addAttachment(Multipart multipart, String fileName)
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) 
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try 
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
         catch (MessagingException e) 
            e.printStackTrace();
        
    

【讨论】:

以上是关于使用 Java 发送邮件附件的主要内容,如果未能解决你的问题,请参考以下文章

java发送邮件

java发送邮件失败!

[Java] JavaMail 发送 html 格式带附件的邮件

用java写一个邮件发送代码

Java使用javax.mail.jar发送邮件并同意发送附件

java Mail 发送外部邮件失败,求解,