以下代码可以很好地与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;
public class GoogleMail {
private GoogleMail() {
}
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);
}
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";
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");
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
final MimeMessage msg = new MimeMessage(session);
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();
}
}
2015年12月11日更新
用户名和密码不再是推荐的解决方案。原因是
我尝试了这个方法,Gmail向使用此代码的电子邮件地址发送了一封电子邮件,指出我们最近阻止了对您的Google帐户的登录尝试,并将我引导到此支持页面:support.google.com/accounts/answer/6010255 因此,为了使其工作,发送电子邮件的帐户需要降低自己的安全级别。
Google发布了Gmail API - https://developers.google.com/gmail/api/?hl=en。我们应该使用oAuth2方法,而不是用户名和密码。
以下是与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;
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();
}
}
以下是构建经过oAuth2授权的Gmail服务的代码片段。
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;
public class Utils {
private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static HttpTransport httpTransport;
private static final Log log = LogFactory.getLog(Utils.class);
static {
try {
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");
}
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 {
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 {
Set<String> scopes = new HashSet<>();
scopes.add("email");
scopes.add(GmailScopes.GMAIL_SEND);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));
return authorize(clientSecrets, scopes, getGmailDataDirectory());
}
private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, scopes)
.setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
.build();
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;
}
}
为了提供用户友好的oAuth2身份验证方式,我使用JavaFX来显示下面的输入对话框。
显示用户友好的oAuth2对话框的关键在于MyAuthorizationCodeInstalledApp.java和SimpleSwingBrowser.java中。