2

我正在尝试发送电子邮件。当我不带附件发送时,它会正确发送电子邮件。如果我尝试附加一些东西,那么它就不起作用。

班上:

import com.sun.mail.smtp.SMTPTransport;

import java.io.File;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    public static void Send(String from, String pass, String[] to, String assunto, String mensagem, File[] anexos) {
        String host = "smtp.risantaisabel.com.br";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        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");

        //String[] to = {"tarcisioambrosio@gmail.com"}; // added this line

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        InternetAddress[] toAddress = new InternetAddress[to.length];
        boolean enviado = true;
        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            try {
                toAddress[i] = new InternetAddress(to[i]);
            } catch (AddressException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
       // System.out.println(Message.RecipientType.TO);

        for( int i=0; i < toAddress.length; i++) { // changed from a while loop
            try {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            message.setSubject(assunto);
            //message.setContent(mensagem, "text/plain");
            message.setText(mensagem);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);

            if(anexos.length == 0){
            }
            else {
                 Multipart mp = new MimeMultipart();          
                 BodyPart messageBodyPart = new MimeBodyPart();  

                for(int i = 0; i < anexos.length;i++) {
                    MimeBodyPart mbp2 = new MimeBodyPart();    

                    FileDataSource fds = new FileDataSource(anexos[i].getPath());  

                    mbp2.setDataHandler(new DataHandler(fds));          
                    mbp2.setFileName(fds.getName());    

                    mp.addBodyPart(mbp2);   
                }
                messageBodyPart.setContent(message, "multipart/mixed");  
                mp.addBodyPart(messageBodyPart); 
                message.setContent(mp);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            JOptionPane.showMessageDialog(null, "<html><b>Email não enviado, tente novamente confirmando seus dados");
            enviado = false;
            e.printStackTrace();
        }
        if(enviado) {
            JOptionPane.showMessageDialog(null, "<html><b>Email enviado.</html></b> \n\n Caso tenha digitado errado o email, somente pela sua caixa de entrada poderá confirmar se chegou. \n\n<html> Email da parte digitado:<b><font size = 3 COLOR=#ff0000> " + to[0]);
        }
    }
}

如果我将 setContent 更改为 text/plain,我会得到:

javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: "text/html" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMessage
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)

如果我将 setContent 更改为 multipart/mixed,我会得到:

javax.mail.MessagingException: MIME part of type "multipart/mixed" contains object of type javax.mail.internet.MimeMessage instead of MimeMultipart

你知道我该如何解决这个问题吗?谢谢。

4

2 回答 2

4

消除

message.setText(mensagem);

改变

messageBodyPart.setContent(message, "multipart/mixed");

messageBodyPart.setText(mensagem);

并将它和以下行移到“for”循环上方。

另外,请参阅他的 JavaMail FAQ entry of common errors

于 2013-09-03T18:24:38.357 回答
1

现在我可以使用 JMS API 发送带有附件和正文内容的邮件。它也适用于我放置多个附件文件。

最终字符串 fromAddress = formBean.getString("fromEmail"); 最终字符串密码=“密码”;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "465");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromAddress, formBean.getString(password));
        }
    });
    Transport transport = null;

    try {
        transport = session.getTransport();
        Message message = new MimeMessage(session);
        String messageBody = "<div style=\"color:red;\">" + formBean.getString("mailBody") + "</div>";
        message.setSentDate(new Date());

        message.setSubject(formBean.getString("subject"));
        // message.setContent(mensagem, "text/plain");

        Multipart mp = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();

        String[] filesNameArray=new String[]{"C:\\Users\\karola\\Desktop\\context.xml","C:\\Users\\karola\\Desktop\\site.xml"};

        for(String fileToAttached:filesNameArray){
            MimeBodyPart mbp2 = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(new File(fileToAttached));
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        messageBodyPart.setText(messageBody);
        mp.addBodyPart(messageBodyPart);
        message.setContent(mp);

        transport.connect();
        message.setReplyTo(InternetAddress.parse(formBean.getString("replyTo")));
        Transport.send(message, InternetAddress.parse(formBean.getString("toAddress")));
        // message(RecipientType.TO,
        // InternetAddress.parse(formBean.getString("toAddress")));
        // transport.sendMessage(message, message.getAllRecipients());
        transport.close();
于 2016-02-07T11:17:17.200 回答