【问题标题】:Send An Email Through Gmail Without JavaMail在没有 JavaMail 的情况下通过 Gmail 发送电子邮件
【发布时间】:2012-03-05 04:28:27
【问题描述】:

我想使用我的 Bukkit(Minecraft 修改平台)的 java 插件发送通知。通过 gmail 帐户发送此通知是最简单的。

我无法让 JavaMail 与 bukkit 一起正常工作,它在独立程序中工作正常。我也不知道将它与我的插件打包是否违反许可条款。

所以我希望能够在没有 JavaMail API 的情况下通过 Gmail 发送电子邮件。 您可能知道,Gmail 需要 SSL 连接或 TLS 连接。

输出:

220-moai.tallduck.com ESMTP Exim 4.69 #1 Mon, 05 Mar 2012 22:14:02 -0700 
220-We do not authorize the use of this system to transport unsolicited, 
220 and/or bulk e-mail.  
250-moai.tallduck.com Hello pool-CENSORED.cncdnh.fast.myfairpoint.net [CENSORED]
250-SIZE 52428800
250-PIPELINING
250-AUTH PLAIN LOGIN
250-STARTTLS
250 HELP
334 CENSORED
334 CENSORED
235 Authentication succeeded
250 OK
500 unrecognized command
250 Accepted
354 Enter message, ending with "." on a line by itself
250 OK id=1S4mio-0001VV-PB
221 moai.tallduck.com closing connection
Done.

邮件确实发送了,但发件人和收件人为空白。

【问题讨论】:

  • 您可以使用JavaMail。没有理由不这样做。

标签: java email gmail


【解决方案1】:

是的,你可以使用socket直接发送消息,例如:

import java.net.*;
import java.io.*;
import java.util.*;

public class SendingEmailUsingSocket {

        public static void main(String[] args) {
                int port = 25; 
                String host = "smtp.gmail.com";

                try {           
                        Socket socket = new Socket(host, port); 

                        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
                        String username = encoder.encode("wajdyessam@gmail.com".getBytes());
                        String password = encoder.encode("yourpassword".getBytes());

                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        DataInputStream is = new DataInputStream(socket.getInputStream());

                        dos.writeBytes("HELO\r\n");
                        dos.writeBytes("AUTH LOGIN");
                        dos.writeBytes("\r\n");
                        dos.writeBytes(username);
                        dos.writeBytes("\r\n");
                        dos.writeBytes(password);
                        dos.writeBytes("\r\n");
                        dos.writeBytes("MAIL FROM:<wajdyessam@hotmail.com>\r\n");
                        dos.writeBytes("\r\n");
                        dos.writeBytes("RCPT TO: <wajdyessam@gmail.com>\r\n");
                        dos.writeBytes("DATA\r\n");
                        dos.writeBytes("Subject: Email test\r\n");
                        dos.writeBytes("Test 1 2 3");
                        dos.writeBytes("\r\n.\r\n");
                        dos.writeBytes("QUIT\r\n");

                        dos.flush();

                        String responseline;
                        while((responseline = is.readLine())!=null) {
                                System.out.println(responseline);
                        }

                        is.close();
                        dos.close( );                  
                        socket.close( );
                } 
                catch (IOException ex) {
                        System.err.println(ex);
                }
        }
}

注意事项: 用户名和密码应该使用 Base64 编码,我使用不推荐使用的方法,但可以随意使用其他方式,例如:Apache Commons 库中的 Base64 编码。

用户名、密码、主题、从和到是硬编码的,如果你想要通用方法,你应该在那里传递字符串。

【讨论】:

  • 谢谢!不过,我对其进行了一些更改,为了摆脱折旧的方法,我这样做了。将DataInputStream is = new DataInputStream(socket.getInputStream()); 替换为:DataInputStream isDI = new DataInputStream(socket.getInputStream()); BufferedReader is = new BufferedReader(new InputStreamReader(isDI));
  • 另外,Base64 编码对我不起作用,所以我使用了来自 http://www.source-code.biz 的 Base64 类
  • 我无法从我所在的位置对其进行测试,因为网络管理员阻止了除 80 之外的所有端口。因此,一旦有机会进行测试,我会将其标记为正确答案。跨度>
  • 我似乎无法让它正常工作,我决定尝试将它与我自己的电子邮件服务器一起使用,但是当电子邮件发送并且我从 gmail 的垃圾邮件文件夹中检索它时,发件人和收件人都是空白!我不知道如何解决这个问题......
  • 用我的输出更新了我原来的问题,如果你能帮忙就太好了
【解决方案2】:

最好还是使用Apache Email API。这也允许您定义 HTML 电子邮件和带有附件的内容。更好的是它经过试验和测试。这是我的插件 CommandsEX 中使用的方法,所以它绝对可以在 Bukkit 中使用!

您可以在我们的 GitHub 存储库中查看其工作原理。确切的类可以在here找到。

【讨论】:

  • 在没有 JavaMail 的情况下特别提到了 OP。 Apache 电子邮件仍然在后台使用 JavaMail。
  • @BennyBottema 感谢您的评论。 OP 说他们很难让 JavaMail 与 Bukkit 一起工作。我的建议来自通过 Bukkit 发送电子邮件的直接经验,它没有明确使用 JavaMail。我认为他在使用 API 时遇到了问题,并提出了一种更简单、经过验证的方法。
【解决方案3】:

这是我为公司制作的应用程序所使用的。 (需要this

变量

    private String SMTP_HOST = "smtp.gmail.com"; 
    private String FROM_ADDRESS = "######@gmail.com"; 
    private String FROM_PASSWORD = "########";
    private String TO_ADDRESS = "###############";
    private String FROM_NAME = "VDRS Lictor Training Application Emailer"; 
    private Properties props = new Properties();

在某些方法中,创建比例

        props.put("mail.smtp.host", SMTP_HOST); 
        props.put("mail.smtp.user",FROM_NAME);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.port", "25");
        props.put("mail.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.EnableSSL.enable","true");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
        props.setProperty("mail.smtp.socketFactory.fallback", "false");  
        props.setProperty("mail.smtp.port", "465");  
        props.setProperty("mail.smtp.socketFactory.port", "465");

当您需要发送时

这是我使用的实际代码。请根据您的需要进行修改。

try{
      JButton b = (JButton) arg0.getSource();
      //button animation
      b.setText("Submitting Application...");
      //get values
      String player = name.getText();
      //make the message
      String msg = "<title>New Lictor Training Application from: " + player + "</title> \n";
      msg+="<h3>[Name]: </h3>" + player + "\n";
      msg+="<h3>[BR]: </h3>" + spinner.getValue() + "\n";
      msg+="<h3>[Platoon Leading Experience]: </h3>" + ((JLabel)    slider.getLabelTable().get(slider.getValue())).getText() + "\n";
      String time = timeEditor.getTextField().getText();
      String[] a = time.split(":");
      int hours = Integer.parseInt(a[0]);
      int min = Integer.parseInt(a[1]);
      calander.getDate().setHours(hours);
      calander.getDate().setMinutes(min);
      calander.getDate().setSeconds(00);
      msg+="<h3>[Date/Time]: </h3>" +  calander.getDate().toGMTString()+"\n";
      msg+="<h3>[Email]: </h3>" + email.getText();
      //set up email
      Session session = Session.getInstance(props, new AuthorizeEmail()); 
      MimeMessage message = new MimeMessage(session);
      try {
        message.setFrom(new InternetAddress(FROM_ADDRESS));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
        message.setSubject("New Outfit Application from: " + player);
        message.setContent(msg, "text/html");
        Transport.send(message);
        b.setText("Application Submitted!");
    } catch (MessagingException e) 
    {
       JOptionPane.showMessageDialog(null, "Failed sending application, please try again later.");
        b.setText("Submit Application");
    }


}catch(NullPointerException e)
   {
       JOptionPane.showMessageDialog(null, "Failed sending application.\n Did you fill out all the fields?.");
      submit.setText("Submit Application");
   }

你也需要这个

class AuthorizeEmail extends Authenticator { 
    @Override
    protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD); 
    } 
}

【讨论】:

  • 在没有JavaMail的情况下特别提到了Op。您的示例直接使用 JavaMail。
猜你喜欢
  • 2011-10-16
  • 2022-08-14
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 2012-01-07
  • 2023-03-19
相关资源
最近更新 更多