簡體   English   中英

如何直接從Java代碼發送帶有附件的私人公司電子郵件?

[英]How to send private companies' emails with attchments directly from Java code?

我很好奇,有沒有辦法直接從Java代碼發送帶有附件的電子郵件。 該電子郵件屬於mylogin @ companyxxx.com公司。即使用Java操作Outlook? 也許我不需要操縱Outlook,而擁有登錄名,密碼和其他人員就足夠了...

是的,您可以使用javamail進行操作 ,也可以從此處下載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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM