使用java发送电子邮件 [英] Send email using java

查看:618
本文介绍了使用java发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java发送电子邮件:

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

public class SendEmail {

public static void main(String [] args){

//需要提及收件人的电子邮件ID。
String to =abcd@gmail.com;

//发件人的电子邮件ID需要被提及
String from =web@gmail.com;

//假设你正在从localhost发送电子邮件
String host =localhost;

//获取系统属性
属性属性= System.getProperties();

//设置邮件服务器
properties.setProperty(mail.smtp.host,host);

//获取默认的Session对象。
会话session = Session.getDefaultInstance(properties);

try {
//创建默认的MimeMessage对象。
MimeMessage message = new MimeMessage(session);

// Set From:头字段的header。
message.setFrom(new InternetAddress(from));

//设置为:标题的标题字段。
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

//设置主题:头字段
message.setSubject(这是主题行!);

//现在设置实际的消息
message.setText(This is actual message);

//发送消息
Transport.send(message);
System.out.println(发送邮件成功....);
} catch(MessagingException mex){
mex.printStackTrace();
}
}
}

我收到错误:

  javax.mail.MessagingException:无法连接到SMTP主机:localhost,port:25; 
嵌套异常是:java.net.ConnectException:连接拒绝:连接
在com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
在com.sun。 mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)

此代码是否可以发送电子邮件?

解决方案

以下代码与Google SMTP服务器非常相似。您需要提供您的Google用户名和密码。

  import com.sun.mail.smtp.SMTPTransport; 
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/ **
*
* @author doraemon
* /
public class GoogleMail {
private GoogleMail(){
}

/ **
*使用GMail SMTP服务器发送电子邮件。
*
* @param用户名GMail用户名
* @param密码GMail密码
* @param recipientEmail TO收件人
* @param消息的标题title
* @param要发送的消息消息
* @throws AddressException如果电子邮件地址解析失败
* @throws MessagingException如果连接死了或不在连接状态,或者消息不是MimeMessage
* /
public static void Send(final String username,final String password,String recipientEmail,String title,String message)throws AddressException,MessagingException {
GoogleMail.Send(username,password,recipientEmail ,,标题,讯息);
}

/ **
*使用GMail SMTP服务器发送电子邮件。
*
* @param用户名GMail用户名
* @param密码GMail密码
* @param recipientEmail TO收件人
* @param ccEmail CC收件人。如果没有CC收件人可以是空的
* @param消息的标题title
* @param要发送的消息消息
* @throws AddressException如果电子邮件地址解析失败
* @throws MessagingException如果连接死或不在连接状态,或者消息不是MimeMessage
* /
public static void Send(final String username,final String password,String recipientEmail, String ccEmail,String title,String message)throws AddressException,MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY =javax.net.ssl.SSLSocketFactory;

//获取属性对象
属性props = System.getProperties();
props.setProperty(mail.smtps.host,smtp.gmail.com);
props.setProperty(mail.smtp.socketFactory.class,SSL_FACTORY);
props.setProperty(mail.smtp.socketFactory.fallback,false);
props.setProperty(mail.smtp.port,465);
props.setProperty(mail.smtp.socketFactory.port,465);
props.setProperty(mail.smtps.auth,true);

/ *
如果设置为false,则会发送QUIT命令,并立即关闭连接。如果将
设置为true(默认值),则导致传输等待对QUIT命令的响应。

ref:http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
http://forum.java .sun.com / thread.jspa?threadID = 5205249
smtpsend.java - javamail中的演示程序
* /
props.put(mail.smtps.quitwait,false) ;

会话session = Session.getInstance(props,null);

// - 创建一条新消息 -
final MimeMessage msg = new MimeMessage(session);

// - 设置FROM和TO字段 -
msg.setFrom(new InternetAddress(username +@ gmail.com));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipientEmail,false));

if(ccEmail.length()> 0){
msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(ccEmail,false));
}

msg.setSubject(title);
msg.setText(message,utf-8);
msg.setSentDate(new Date());

SMTPTransport t =(SMTPTransport)session.getTransport(smtps);

t.connect(smtp.gmail.com,用户名,密码);
t.sendMessage(msg,msg.getAllRecipients());
t.close();
}
}



2015年12月11日更新



用户名+密码不再是推荐的解决方案。这是由于


我试过这个,Gmail在这段代码中发送了用作用户名的电子邮件,一封
电子邮件,说我们最近阻止了您的Google
帐户的登录尝试,并指示我进入此支持页面:
support.google.com/accounts/answer/6010255,以便它可以工作,
用于发送的电子邮件帐户需要减少自己的
安全性


Google发布了Gmail API -



显示用户友好的oAuth2对话框的关键可以在 MyAuthorizationCodeInstalledApp.java SimpleSwingBrowser.java


I'm trying to send an email using Java:

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

public class SendEmail {

   public static void main(String [] args) {

      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // 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.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

I am getting the error :

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)

Will this code work to send email?

解决方案

The following code works very well with Google SMTP server. You need to supply your Google username and password.

import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, message);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set 
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());      
        t.close();
    }
}

Update on 11 December 2015

Username + password is no longer a recommended solution. This is due to

I tried this and Gmail sent the email used as username in this code an email saying that We recently blocked a sign-in attempt to your Google Account, and directed me to this support page: support.google.com/accounts/answer/6010255 so it looks for it to work, the email account being used to send needs to reduce their own security

Google had released Gmail API - https://developers.google.com/gmail/api/?hl=en. We should use oAuth2 method, instead of username + password.

Here's the code snippet to work with Gmail API.

GoogleMail.java

import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText) throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);
        InternetAddress tAddress = new InternetAddress(to);
        InternetAddress cAddress = cc.isEmpty() ? null : new InternetAddress(cc);
        InternetAddress fAddress = new InternetAddress(from);

        email.setFrom(fAddress);
        if (cAddress != null) {
            email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
        }
        email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

    public static void Send(Gmail service, String recipientEmail, String ccEmail, String fromEmail, String title, String message) throws IOException, MessagingException {
        Message m = createMessageWithEmail(createEmail(recipientEmail, ccEmail, fromEmail, title, message));
        service.users().messages().send("me", m).execute();
    }
}

To construct an authorized Gmail service through oAuth2, here's the code snippet.

Utils.java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.yccheok.jstock.engine.Pair;

/**
 *
 * @author yccheok
 */
public class Utils {
    /** Global instance of the JSON factory. */
    private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static final Log log = LogFactory.getLog(Utils.class);

    static {
        try {
            // initialize the transport
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        } catch (IOException ex) {
            log.error(null, ex);
        } catch (GeneralSecurityException ex) {
            log.error(null, ex);
        }
    }

    private static File getGmailDataDirectory() {
        return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
    }

    /**
     * Send a request to the UserInfo API to retrieve the user's information.
     *
     * @param credentials OAuth 2.0 credentials to authorize the request.
     * @return User's information.
     * @throws java.io.IOException
     */
    public static Userinfoplus getUserInfo(Credential credentials) throws IOException
    {
        Oauth2 userInfoService =
            new Oauth2.Builder(httpTransport, JSON_FACTORY, credentials).setApplicationName("JStock").build();
        Userinfoplus userInfo  = userInfoService.userinfo().get().execute();
        return userInfo;
    }

    public static String loadEmail(File dataStoreDirectory)  {
        File file = new File(dataStoreDirectory, "email");
        try {
            return new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
        } catch (IOException ex) {
            log.error(null, ex);
            return null;
        }
    }

    public static boolean saveEmail(File dataStoreDirectory, String email) {
        File file = new File(dataStoreDirectory, "email");
        try {
            //If the constructor throws an exception, the finally block will NOT execute
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            try {
                writer.write(email);
            } finally {
                writer.close();
            }
            return true;
        } catch (IOException ex){
            log.error(null, ex);
            return false;
        }
    }

    public static void logoutGmail() {
        File credential = new File(getGmailDataDirectory(), "StoredCredential");
        File email = new File(getGmailDataDirectory(), "email");
        credential.delete();
        email.delete();
    }

    public static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws Exception {
        // Ask for only the permissions you need. Asking for more permissions will
        // reduce the number of users who finish the process for giving you access
        // to their accounts. It will also increase the amount of effort you will
        // have to spend explaining to users what you are doing with their data.
        // Here we are listing all of the available scopes. You should remove scopes
        // that you are not actually using.
        Set<String> scopes = new HashSet<>();

        // We would like to display what email this credential associated to.
        scopes.add("email");

        scopes.add(GmailScopes.GMAIL_SEND);

        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
            new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));

        return authorize(clientSecrets, scopes, getGmailDataDirectory());
    }

    /** Authorizes the installed application to access user's protected data.
     * @return 
     * @throws java.lang.Exception */
    private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
        // Set up authorization code flow.

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
            .build();
        // authorize
        return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static Gmail getGmail(Credential credential) {
        Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("JStock").build();
        return service;        
    }
}

To provide a user friendly way of oAuth2 authentication, I made use of JavaFX, to display the following input dialog

The key to display user friendly oAuth2 dialog can be found in MyAuthorizationCodeInstalledApp.java and SimpleSwingBrowser.java

这篇关于使用java发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆