使用 Java 发送邮件附件

2022-01-23 00:00:00 email gmail email-attachments java

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

I am trying to send an email using Java and Gmail. I have stored my files on the cloud and the stored files I want to send as an attachment to my email.

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

It should add those files to this mail and not links of those files.

如何发送此类附件?

推荐答案

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

Working code, I have used 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();
    }
  }
}

相关文章