Java邮件与Java Mail api

时间:2012-05-22 09:31:07

标签: java email javamail

我在我的项目中使用JavaMail api发送邮件。但是当我编写用邮件附加文件的代码时,发送邮件需要很多时间。而5次中有4次会给出连接超时错误。我不能找出它的具体原因。文件数据大约是400到500 KB 这是代码

public static void sendMailTo(String receiverEmailID, String emailSubject,String emailBody,ArrayList<String> attachmentFilepath) throws AddressException, MessagingException, IOException {

        Properties properties = new Properties();           
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.text", "text/plain");
        properties.put("mail.smtp.debug", "true");

        // Authentication For Sender.
        if (session == null)
            session = Session.getInstance(properties,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication("username","password"
                            );
                        }
                    });

        // This block process to send mail on particular UserID
        Message message = new MimeMessage(session); 
        message.setFrom(new InternetAddress(""));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(receiverEmailID));
        message.setSubject(emailSubject);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(emailBody, "text/html");
        messageBodyPart.setDisposition(Part.INLINE);
        Multipart multipart = new MimeMultipart("mixed");

        multipart.addBodyPart(messageBodyPart); 
        int i=0;
        while(i<attachmentFilepath.size()){
              BodyPart attachment = new MimeBodyPart();
              DataSource source = new FileDataSource(new File(attachmentFilepath.get(i)));
              attachment.setDataHandler(new DataHandler(source));
              attachment.setFileName(source.getName());
              attachment.setDisposition(Part.ATTACHMENT);
              multipart.addBodyPart(attachment);              
              i++;
        }    
        message.setContent(multipart);
        Transport.send(message);// This statement send Message.             
    }

1 个答案:

答案 0 :(得分:0)

尝试 ping smtp.gmail.com -t

你丢失了包裹吗?如果是,这是您的问题的答案(网络问题)