javax.mail.MessagingException的:

时间:2015-06-20 10:06:24

标签: java email javamail

package com.mca2b;
import java.util.Properties;
import javax.mail.util.*;
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  


public class SampleMail 
{
     public static void main(String [] args) throws Exception{  
          String to = "kalgaonkarsiddhesh@gmail.com";//change accordingly  
          String from = "siddhesh.kalgaonkar@ves.ac.in";//change accordingly  
          String host = "localhost";//or IP address  
          // Get system properties
          Properties properties = System.getProperties();

          // Setup mail server
          properties.setProperty("mail.smtp.host", host);

          // Get the default Session object.
          Session session = Session.getDefaultInstance(properties);

          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (SendFailedException mex) {
             mex.printStackTrace();
          }

     }  

}

我在线程“main”javax.mail.MessagingException中遇到Exception。无法连接到SMTP主机:localhost,port:25嵌套异常是:java.net.ConnectException:连接被拒绝:连接。那么解决方案是什么?

我在这里发布了正确的代码,用于在struts 2中通过gmail发送邮件。对于不同的提供商,您必须相应地更改SMTP主机:)

package org.entity;

import com.opensymphony.xwork2.ActionSupport;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 DonorForgotAction extends ActionSupport
{
DonorForgot forg;
    public DonorForgotAction() {
    // TODO Auto-generated constructor stub
}
    public DonorForgot getForg() {
        return forg;
    }
    public void setForg(DonorForgot forg) {
        this.forg = forg;
    }
    @Override
    public String execute() throws Exception {
        String email,pass;
        final String username = "";
        final String password = "";
        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");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/foryou", "root", "siddheshkk");
            System.out.println("Driver Loaded");
            PreparedStatement ps = con
                    .prepareStatement("select email,password from donorinfo where contact=?");
            ps.setString(1, forg.getContact());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                email=rs.getString("email");
                pass=rs.getString("password");
                System.out.println("Here is your email id "+email+"and password is "+pass);
                try {
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(username));
                    message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(email));
                    message.setSubject("Password Retrieval");
                    message.setText("Dear user your password is "+ pass);
                    Transport.send(message);
                    System.out.println("Done");

                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                return "success";
            } else {
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

}

1 个答案:

答案 0 :(得分:1)

你忘记了两个步骤:

  • 您的密码

  • The Authenticator

此外,您可能没有任何本地邮件服务器监听本地主机上的端口25(javax.mail.MessagingException)。

这里我使用端口587。

所以试试这段代码:

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


public class SampleMail 
{
     public static void main(String [] args) throws Exception
     {  
          final String from = "siddhesh.kalgaonkar@ves.ac.in"; // change accordingly
          final String password = "yourPassword"; // change accordingly
          String to = "kalgaonkarsiddhesh@gmail.com"; // change accordingly
          String host = "localhost"; // or IP address

          // Get system properties
          Properties properties = System.getProperties();

          // Setup mail server
          properties.put("mail.smtp.host", host);
          properties.put("mail.smtp.port", 587);
          properties.put("mail.smtp.auth", "true");
          properties.put("mail.smtp.starttls.enable", "true");
          properties.put("mail.user", from);
          properties.put("mail.password", password);

          // Get the default Session object.
          Authenticator auth = new Authenticator()
          {
              public PasswordAuthentication getPasswordAuthentication()
              {
                  return new PasswordAuthentication(from, password);
              }
          };
          Session session = Session.getInstance(properties, auth);

          try
          {
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }
          catch (SendFailedException mex)
          {
             mex.printStackTrace();
          }
     }
}

我使用此代码,如果这可以帮助您:

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


class SampleMail
{
    public static void main(String args[]) throws Exception
    {
        new Email("yourEmail(sendTheMessage)", "yourEmailPassword", "yourEmail(recvTheMessage)", "subject", "message"); // Send a message

        String[] attachments = {"/home/user/Documents/text.odt"};
        new Email("yourEmail(sendTheMessage)", "yourEmailPassword", "yourEmail(recvTheMessage)", "subject", "message", attachments); // send a message with attachments
    }
}

class Email
{
    private String host, port = "587";

    Email(String mailFrom, String password, String mailTo, String subject, String message) throws Exception
    {
        if (mailFrom.contains("@gmail"))
            this.host = "smtp.gmail.com";
        else if (mailFrom.contains("@yahoo"))
            this.host = "smtp.mail.yahoo.com";
        else
            this.host = "smtp.live.com";

        sendEmail(host, port, mailFrom, password, mailTo, subject, message, null);
    }

    Email(String mailFrom, String password, String mailTo, String subject, String message, String[] attachFiles) throws Exception
    {
        if (mailFrom.contains("@gmail"))
            this.host = "smtp.gmail.com";
        else if (mailFrom.contains("@yahoo"))
            this.host = "smtp.mail.yahoo.com";
        else
            this.host = "smtp.live.com";

        sendEmail(host, port, mailFrom, password, mailTo, subject, message, attachFiles);
    }

    private void sendEmail(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws Exception
    {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.user", userName);
        properties.put("mail.password", password);

        Authenticator auth = new Authenticator()
        {
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(userName, password);
            }
        };
        Session session = Session.getInstance(properties, auth);

        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(message, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        if (attachFiles != null && attachFiles.length > 0)
        {
            for (String filePath : attachFiles)
            {
                MimeBodyPart attachPart = new MimeBodyPart();

                try
                {
                    attachPart.attachFile(filePath);
                }
                finally
                {
                    multipart.addBodyPart(attachPart);
                }
            }
        }
        msg.setContent(multipart);

        Transport.send(msg);
    }
}

但是在这里,您必须更改主机以允许其他内容而不是gmail,yahoo或hotmail帐户。