使用Java发送邮件附件



我正在尝试使用Java和Gmail发送电子邮件。我已经把我的文件存储在云上,我想把存储的文件作为附件发送到我的电子邮件。

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

如何发送这样的附件?

工作代码,我使用了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();
    }
  }
}

由于未知的原因,当我将电子邮件发送到我的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

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

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

要了解如何配置您的项目来处理这些代码,请阅读本教程。

这对我很有效。

这里我假设我的附件是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);
        }
    }
} 

如果你允许的话,对于多附件,上面第一个nincomoop的答案也很好,只需要做一些修改,如下所示:

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

发送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();
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新