在没有JavaMail的情况下通过Gmail发送电子邮件

时间:2012-03-05 04:28:27

标签: java email gmail

我想通过我的java插件发送Bukkit通知(A Minecraft修改平台)通过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.

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

3 个答案:

答案 0 :(得分:3)

是的,您可以使用套接字直接发送消息,例如:

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编码。

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

答案 1 :(得分:1)

更好的是,您可以使用Apache Email API。这允许您定义HTML电子邮件和附件的东西。更好的是它经过了试验和测试。这是我的插件CommandsEX中使用的方法,因此它绝对适用于Bukkit!

您可以在我们的GitHub回购中查看它是如何工作的。可以找到确切的类here

答案 2 :(得分:-1)

这就是我用于公司的应用程序。 (需要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); 
    } 
}