如何使用javacode发送电子邮件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23286244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:40:38  来源:igfitidea点击:

How to send email using javacode?

javajavamail

提问by user3493831

Hi i am trying to send email through java code i am i have installed cmail server for sending email but i am not able to send email how can i send email

嗨,我正在尝试通过 Java 代码发送电子邮件,我已经安装了用于发送电子邮件的 cmail 服务器,但我无法发送电子邮件,我该如何发送电子邮件

here is my code

这是我的代码

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

public class SendEmail  
{  
 public static void main(String [] args){  
      String to = "[email protected]";//change accordingly  
      String from = "[email protected]";
      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();}  
   }  
} 

when i run my program i am getting following Exception

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

com.sun.mail.smtp.SMTPSendFailedException: 550 [email protected] is not authorized.(WRONG SENDER MAILADDR)
;
  nested exception is:
    com.sun.mail.smtp.SMTPSenderFailedException: 550 [email protected] 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 [email protected] is not authorized.(WRONG SENDER MAILADDR)

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

How can i achieve my output?

我怎样才能实现我的输出?

Thanks in advance

提前致谢

采纳答案by Aditya Ekbote

You have not given a password field in it. Additionally you have not specified your host. If you are sending email from local host, you should specify it. Also if you are sending mail by gmail server, you should use "smtp.gmail.com". Check http://www.tutorialspoint.com/servlets/servlets-sending-email.htmfor clarifying your problem. From this tutorial you can send email with attachment too. And if you need code in jsp, I can provide you.

您没有在其中提供密码字段。此外,您还没有指定您的主机。如果您从本地主机发送电子邮件,则应指定它。此外,如果您通过 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;        //"[email protected]" // 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>

回答by Pramod S. Nikam

You need to athenticate your email before sending add below code after setting properties ,

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

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

and use

并使用

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

instead of

代替

  Session session = Session.getDefaultInstance(properties);  

and if you dont want use authentication then set below property,

如果您不想使用身份验证,请设置以下属性,

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

回答by Bill Shannon

The problem appears to be in the configuration of your mail server. Is your mail server running on the machine "shakti-pc.com"? If not, it's (rightly) preventing you from saying that your address is [email protected] so that you can't send email with a faked from address.

问题似乎出在邮件服务器的配置中。您的邮件服务器是否在“shakti-pc.com”机器上运行?如果不是,它(正确地)阻止你说你的地址是 [email protected],这样你就不能用伪造的发件人地址发送电子邮件。

Also, unrelated to your current problem, you might want to fix these common mistakesin your program or in any code you've copied from others.

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

回答by user4128375

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

测试自动化

回答by Karnan Kurup

use ssl connection with port 465

使用 465 端口的 ssl 连接

To enable ssl set

启用 ssl 集

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

and to avoid exception 530 certification error add

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

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