使用java发送电子邮件时出错

时间:2014-10-15 12:10:44

标签: java

我正在尝试向使用Java的人发送电子邮件。我尝试使用以下代码,但它无法正常工作。我找不到我的程序中发生的错误..

见下面是我的代码,

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestMailsending {

    /**
     * @param args
     */
    public static void main(String[] args) {

        final String username = "myemailid@gmail.com";
        final String password = "mypassword";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        /*try {
            Session session = Session.getDefaultInstance(props, null);     

            MimeMessage message = new MimeMessage(session);     

            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++ ) { // changed from a while loop         
                toAddress[i] = new InternetAddress(to[i]);     
                }     

            System.out.println(Message.RecipientType.TO);       

            for( int i=0; i < toAddress.length; i++) { // changed from a while loop         
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);     
                }     

            message.setSubject("Test Mail");     
            message.setText("This is a test mail confirmation. Regards, Mr.XXX");     

            Transport transport = session.getTransport("smtp");     
            transport.connect(host, from, pass);     
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            } catch (Exception e)
            {
                System.out.println(e.toString());
            }*/
        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("from-myemailid@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("someonesid@gmail.com"));
            message.setSubject("Test Mail");
            message.setText("Hai,"
                + "\n\n This is test mail configuration Thank you...");

            Transport.send(message);

            System.out.println("Done");
        } 
        catch (MessagingException e) 
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

}

此代码无法正常运行请帮助我......

1 个答案:

答案 0 :(得分:1)

以下代码将帮助您,它为我工作,

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Email {

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

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; // list of recipient email addresses
    String subject = "Java send mail example";
    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.ssl.trust", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");//587
    props.put("mail.smtp.auth", "true");


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

    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]);
        }



        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();
    }
 }
 }

如果此代码不适合您,请检查jar文件