如何使用java代码发送电子邮件?

时间:2014-04-25 07:00:14

标签: java javamail

您好我正在尝试通过java代码发送电子邮件我已经安装了cmail服务器用于发送电子邮件但我无法发送电子邮件如何发送电子邮件

这是我的代码

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

public class SendEmail  
{  
 public static void main(String [] args){  
      String to = "shaktisharma27789@gmail.com";//change accordingly  
      String from = "admin@shakti-pc.com";
      String host = "localhost";//or IP address  

     //Get the session object  
      Properties properties = System.getProperties();  
      properties.setProperty("mail.smtp.host", host);  
      Session session = Session.getDefaultInstance(properties);  

     //compose the message  
      try{  
         MimeMessage message = new MimeMessage(session);  
         message.setFrom(new InternetAddress(from));  
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
         message.setSubject("Ping");  
         message.setText("Hello, this is example of sending email  ");  

         // Send message  
         Transport.send(message);  
         System.out.println("message sent successfully....");  

      }catch (MessagingException mex) {mex.printStackTrace();}  
   }  
} 

当我运行我的程序时,我得到了以下异常

com.sun.mail.smtp.SMTPSendFailedException: 550 admin@shakti-pc.com is not authorized.(WRONG SENDER MAILADDR)
;
  nested exception is:
    com.sun.mail.smtp.SMTPSenderFailedException: 550 admin@shakti-pc.com is not authorized.(WRONG SENDER MAILADDR)

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
    at SendEmail.main(SendEmail.java:27)
Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 550 admin@shakti-pc.com is not authorized.(WRONG SENDER MAILADDR)

    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1616)
    ... 4 more

我如何实现输出?

提前致谢

5 个答案:

答案 0 :(得分:2)

您尚未在其中输入密码字段。此外,您尚未指定主持人。如果要从本地主机发送电子邮件,则应指定该电子邮件。此外,如果您通过gmail服务器发送邮件,则应使用" smtp.gmail.com"。 请检查http://www.tutorialspoint.com/servlets/servlets-sending-email.htm以澄清您的问题。在本教程中,您也可以发送带附件的电子邮件。如果您需要jsp中的代码,我可以为您提供。

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Mail Program</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
<body>
<%@page import="java.sql.*"%>
<%@page import="javax.mail.*"%>

<%@page import="javax.mail.internet.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@ page import="java.math.BigInteger"%>



<%
        String host = "smtp.gmail.com";
    //host = smtp_server; //"smtp.gmail.com"; user = jsp_email;        //"YourEmailId@gmail.com" // email id to send the emails
//pass = jsp_email_pw; //Your gmail password
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String to_add = request.getParameter("receiver");
String subject =request.getParameter("subject"); 
String messageText =request.getParameter("body"); 
String password = request.getParameter("pwd");
String from =request.getParameter("email_id");
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to_add) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setContent(messageText, "text/html"); // use setText if you want to send text
Transport transport = mailSession.getTransport("smtp");
System.setProperty("javax.net.ssl.trustStore", "conf/jssecacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "admin");
transport.connect(host, from, password);
try 
{
    transport.sendMessage(msg, msg.getAllRecipients());
    out.println("sent");
    //WasEmailSent = true; // assume it was sent
}
catch (Exception err) 
{
    //WasEmailSent = false; // assume it's a fail
    out.println("Error" + err.getMessage());
}
transport.close();
%>
</body>
</html>

答案 1 :(得分:1)

在设置属性后,您需要在发送添加以下代码之前验证您的电子邮件,

Authenticator authenticator = new Authenticator () {
    public PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication("user" "password");
    }
};

并使用

 Session session = Session.getDefaultInstance( props , authenticator);  

而不是

  Session session = Session.getDefaultInstance(properties);  

如果你不想使用身份验证,那么设置下面的属性,

  properties.setProperty("mail.smtp.auth", "false");

答案 2 :(得分:0)

问题似乎出现在邮件服务器的配置中。您的邮件服务器是否在计算机“shakti-pc.com”上运行?如果没有,它(正确地)阻止您说您的地址是admin@shakti-pc.com,这样您就无法发送带有伪造地址的电子邮件。

此外,与您当前的问题无关,您可能希望在程序或您从其他人复制的任何代码中修复这些common mistakes

答案 3 :(得分:0)

Use jdk 1.6 or 1.7 for sending emails.. JDk 1.8 throws exceptions frequently while sending mails.

Below I have pasted the sample code to send the mail

 public static void mail(){
      String host="HostName"
      final String user="SenderMailID"
      final String password="Password"
      final String senderName="senderName";
      final String subjectName="name"
      String[] to=getArrayOfEmails("ToEmail");
      String[] cc=getArrayOfEmails("CcEmail");
       Properties props = new Properties();
       props.put("mail.smtp.host",host);
       props.put("mail.smtp.auth", "true");
     //props.put("mail.smtp.starttls.enable", "true");
       Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user,password);
          }
        });
        try {
         MimeMessage message = new MimeMessage(session);
         message.setFrom(new InternetAddress(senderName + "<" + user + ">"));

         for(int i=0;i<to.length;i++)
         {
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to[i]));
        }
         for(int i=0;i<cc.length;i++)
         {
             message.addRecipient(Message.RecipientType.CC,new InternetAddress(cc[i]));
        }
         message.setSubject("subjName");
         BodyPart messageBodyPart = new MimeBodyPart();
         messageBodyPart.setText("bodyText");
         Multipart multipart = new MimeMultipart();
         multipart.addBodyPart(messageBodyPart);
         messageBodyPart = new MimeBodyPart();
         Transport.send(message);
         } catch (MessagingException e) {e.printStackTrace();}`enter code here`
     }

Test Automation

答案 4 :(得分:0)

使用ssl连接端口465

启用ssl set

props.put("mail.smtp.ssl.enable", true);

并避免异常530认证错误添加

MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sf);
相关问题