1.安裝jar檔
mail.jar
activation.jar
additionnal.jar
將這三個檔案下載到專案的libs資料夾上,接著在eclips重新整理專案,在這三個檔案按右鍵->Bulid Path-> Add to Build Path 完成
2.在src新增建立資料夾com,在資料夾com裡面再建立一個資料夾provider,接著再eclips裡此資料夾下建立
JSSEProvider.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*/
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
3.在自己的專案src資料夾下建立GMailSender.java
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Log.i("user::::::::", user);
Log.i("password::::::::", password);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
Log.i("subject::::::::", subject);
Log.i("body::::::::", body);
Log.i("sender::::::::", sender);
Log.i("recipients::::::::", recipients);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
/*******2015.09.29 附加圖片*******/
// create multipart
Multipart multipart = new MimeMultipart();
// create bodypart with image and set content-id
MimeBodyPart messageBodyPart = new MimeBodyPart();
File testImage = new File("/storage/emulated/0/Download/", "test.png"); //手機檔案位置,檔案名稱
DataSource source = new FileDataSource(testImage);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("image.png");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setHeader("Content-ID","");
multipart.addBodyPart(messageBodyPart);
// create bodypart with html content and reference to the content-id
messageBodyPart = new MimeBodyPart();
String htmlText = "
";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
// add multipart to message
message.setContent(multipart);
/***************參考來源 http://goo.gl/OAZn5q ****************/
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
Log.i("eeeeee::::::::", e+"");
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
4.接著在想觸發的檔案上加上此段code
try {
GMailSender sender = new GMailSender("username@gmail.com", "password"); //寄件者(開發方)帳號與密碼
sender.sendMail("This is Subject", //信件標題
"This is Body", //信件內容
"username@gmail.com", //寄件者
"user@yahoo.com"); //收件者
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
5.可能發生問題在 Log.i("eeeeee::::::::", e+"");A.android.os.NetworkOnMainThreadException 在MainActivity.java加上此段
/* 加入StrictMode避免發生 android.os.NetworkOnMainThreadException */
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
B.javax.mail.AuthenticationFailedException
此為無法登入帳號,可能是帳號密碼錯誤,或是帳號未設定
此時GMail會收到信,點選連結變更設定https://www.google.com/settings/security/lesssecureapps
啟動IMAP
完成
參考資料:
http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a/2033124#2033124
http://stackoverflow.com/questions/1334802/how-can-i-use-external-jars-in-an-android-project/6859020#6859020
http://bbs.csdn.net/topics/310000387
http://stackoverflow.com/questions/7398382/embedd-inline-images-using-java-mail-in-android
檔案位置:https://github.com/terryyamg/AutoEmail


