如何直接从Java代码发送带有附件的私人公司的电子邮件?

时间:2013-10-11 06:10:02

标签: java outlook

我很好奇有没有办法直接从Java代码发送附件的电子邮件。该电子邮件属于公司mylogin @ companyxxx.com` I.e。使用Java操纵Outlook?或者也许我不需要操纵Outlook,只需要登录和密码以及其他工作人员......

1 个答案:

答案 0 :(得分:2)

是的,您可以使用javamail执行此操作,您可以从here下载jar。对于outlook,您只需按如下方式设置属性:

    Properties props = new Properties();
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.host", "smtp.live.com");
    props.put("mail.smtp.port", "25");
    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");
    props.setProperty("mail.smtp.port", "587");
    props.setProperty("mail.smtp.socketFactory.port", "587");

或者如果您想要完整示例,请使用以下方法:

    public int sendMailWithAttachment(String to, String subject, String body, String filepath, String sendFileName) {
    final String username = "YOUR EMAIL";
    final String password = "YOUR PWD";
    Properties props = new Properties();
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.host", "smtp.live.com");
    props.put("mail.smtp.port", "25");
    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");
    props.setProperty("mail.smtp.port", "587");
    props.setProperty("mail.smtp.socketFactory.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(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<html><body>HELLO</body></html>", "text/html");
        DataSource source = new FileDataSource(filepath);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(sendFileName);
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);
        Transport.send(message);
        return 1;
    } catch (Exception e) {
        return 0;
    }
}