使用Java发送电子邮件..附件代码不起作用?

时间:2013-12-30 15:10:37

标签: java javamail

我刚尝试通过java代码发送电子邮件。实际上它工作正常,没有任何错误。但是,当我收到电子邮件时,它不包含附件,根据代码应该("try.txt")

我根本不知道JavaMail我刚刚完成了这段代码并尝试了这个

代码

import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

public class Main {

    private static String USER_NAME = "******";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "*******"; // GMail password
    private static String RECIPIENT = "*******";


    public static void main(String[] args) {
        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Find An Attachment";
        String body = "Welcome to JavaMail!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);
        //session.setDebug(true);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }


            BodyPart messageBodyPart = new MimeBodyPart();

                // Fill the message
            messageBodyPart.setText("This is message body");

            // Create a multipar message
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            //attachment
            messageBodyPart = new MimeBodyPart();
            String filename = "C:/try.txt";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);
            message.setSubject(subject);
            message.setText(body);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();


        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
    }
}

要正确发送附件需要添加哪些特殊内容?

请指导我。

提前致谢

3 个答案:

答案 0 :(得分:2)

从代码中删除此行

message.setText(body);

setText()内部调用setContent()函数。因此,如果您在setText()之后调用setContent函数,则它基本上会覆盖您最初设置的内容。

有关详细信息,请参阅this

答案 1 :(得分:0)

试试这个:

MimeBodyPart mimeBody = new MimeBodyPart();
mimeBody.attachFile(file);

MimeMultipart mimeMulti = new MimeMultipart();
mimeMulti.addBodyPart(mimeBody);

msg.setContent(mimeMulti);

答案 2 :(得分:0)

我遇到了以编程方式发送带附件的电子邮件的类似挑战。我像这样使用Apache Commons Email

            public static final String ATTACHMENT_PATH = "/opt/testfile/example_4mb_file.mp4";

            // Create the attachment
    File attachFile = new File(ATTACHMENT_PATH);
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath(attachFile.getAbsolutePath());
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription(attachFile.getName());
    attachment.setName(attachFile.getName());

    // Create the email message
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(465);
    email.setAuthenticator(new DefaultAuthenticator(
            EMAIL_USERNAME,
            EMAIL_PASSWORD));
    email.setSSLOnConnect(true);
    email.addTo(EMAIL_RECEIVER);
    email.setFrom(EMAIL_SENDER, EMAIL_SUBJECT);
    email.setSubject("TestMail id " + this.uniqueId);
    email.setMsg("This is a test attachment mail ... :-)");

    // add the attachment
    email.attach(attachment);

    // send the email
    email.send();
相关问题