Sending an email with an attachment using javamail API

后端 未结 5 974
遥遥无期
遥遥无期 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: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);
            }
        }
    }
    

提交回复
热议问题