如何使用GMail,Yahoo或Hotmail通过Java应用程序发送电子邮件?

Bil*_*ard 200 java email gmail jakarta-mail mail-server

是否可以使用GMail帐户从我的Java应用程序发送电子邮件?我已经使用Java应用程序配置我的公司邮件服务器来发送电子邮件,但是当我分发应用程序时,这不会削减它.任何使用Hotmail,Yahoo或GMail的答案都是可以接受的.

Bil*_*ard 186

首先下载JavaMail API并确保相关的jar文件在您的类路径中.

这是使用GMail的完整工作示例.

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

public class Main {

    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "********"; // GMail password
    private static String RECIPIENT = "lizard.bill@myschool.edu";

    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.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");

        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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您需要在catch块中执行更多操作,而不是像上面的示例代码中那样打印堆栈跟踪.(删除catch块以查看从JavaMail API调用哪些方法抛出异常,以便您可以更好地了解如何正确处理它们.)


感谢@jodonnel和其他所有回答的人.我给了他一笔赏金,因为他的回答让我得到了95%的完整答案.

  • 我无法使用带有上述和类似代码的SMTP gmail访问并获得`javax.mail.AuthenticationFailedException`并且必须在我的Gmail设置中明确启用"安全性较低的应用程序":https://www.google.com/settings /安全/ lesssecureapps.一旦启用"安全性较低的应用程序",代码就可以运行 (6认同)
  • 对于SSL gmail连接,请使用props.put("mail.smtp.port","465"); //而不是587 (2认同)
  • 有关Session.getDefaultInstance(properties)的使用,请参阅http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance.此FAQ建议使用getInstance(..). (2认同)

jod*_*ell 109

这样的事情(听起来你只需要更改你的SMTP服务器):

String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
    to_address[i] = new InternetAddress(to[i]);
    i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {

    message.addRecipient(Message.RecipientType.TO, to_address[i]);
    i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Run Code Online (Sandbox Code Playgroud)

  • 要发送html正文而不是明文更改此行:`message.setText("Welcome to JavaMail");`with this line:`message.setContent("<h1> Hello world </ h1>","text/html ");` (4认同)
  • 缺少这个("mail.smtp.starttls.enable","true") (4认同)

Jas*_*her 20

其他人在上面有很好的答案,但我想在这里添加一个关于我的经验的说明.我发现当使用Gmail作为我的网络应用程序的出站SMTP服务器时,Gmail只允许我发送大约10条消息,然后才能使用反垃圾邮件响应进行响应,我必须手动单步重新启用SMTP访问.我发送的电子邮件不是垃圾邮件,但是当用户在我的系统注册时,网站是"欢迎"电子邮件.所以,YMMV,我不会依赖Gmail生产webapp.如果您代表用户发送电子邮件,例如已安装的桌面应用(用户输入自己的Gmail凭据),您可能没问题.

此外,如果您使用的是Spring,那么这是一个使用Gmail进行出站SMTP的工作配置:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="host" value="smtp.gmail.com"/>
    <property name="port" value="465"/>
    <property name="username" value="${mail.username}"/>
    <property name="password" value="${mail.password}"/>
    <property name="javaMailProperties">
        <value>
            mail.debug=true
            mail.smtp.auth=true
            mail.smtp.socketFactory.class=java.net.SocketFactory
            mail.smtp.socketFactory.fallback=false
        </value>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)


小智 12

即使这个问题已经结束,我想发布一个反制解决方案,但现在使用Simple Java Mail(开源JavaMail smtp包装器):

final Email email = new Email();

String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"to@gmail.com"};

email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
    email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");

new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);
Run Code Online (Sandbox Code Playgroud)

  • 我收到该代码的错误:"消息:通用错误:530 5.7.0必须首先发出STARTTLS命令" - 如何启用vesijama的starttls? (2认同)

Rip*_*sim 7

我的完整代码如下:

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

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "test@gmail.com";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "ripon420@yahoo.com";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // 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 transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}
Run Code Online (Sandbox Code Playgroud)