Sending an email with an attachment using javamail API

后端 未结 5 973
遥遥无期
遥遥无期 2020-12-06 12:10

I am trying to send an email with an attachment file in Java.

When I send the email without an attachment I receive the email, but when I add the attachment I don\'t

相关标签:
5条回答
  • 2020-12-06 12:20

    An email message consists of a header and body segment.

    Header part will contain from, to and subject.

    The body contains the attachments. To support carrying attachments in the body, type Multipart should exists.

    The Multipart object holds multiple parts in which each part is represented as a type of BodyPart whose subclass, MimeBodyPart – can take a file as its content.

    To add attachments into the mail body MimeBodyPart class provides some convenient methods.

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

    For more info refer this link.

    https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm

    0 讨论(0)
  • 2020-12-06 12:25

    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

    0 讨论(0)
  • 2020-12-06 12:26
    1. Disable Your Anti Virus

    because you have some warning like this

    warning message form antivirus

    Try this code... It Help You....

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 12:31

    See the JavaMail FAQ for debugging tips. In particular, the protocol trace will tell you more about what's going on in each case. While you're there you'll find tips for using GMail as well.

    If the only difference is really just the addition of an attachment, it seems unlikely that it's an authentication problem. You may be getting an exception that you're not noticing since your send method is declared to throw MessagingException.

    0 讨论(0)
  • 2020-12-06 12:44

    You can access the gmail using the username and password. But access will be denied by gmail account.

    So, you have to change the security level by going to account settings, password section and disbale the verification code security settings or lower your security level depends on the old or latest gmail application.

    If you want to send the attachment through gmail by accessing the local directory, then you need to use the File object to be set to DataSource constructor class as directed in the program below. This will avoid "Access denied" exception.

    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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题