下面是我在應用程序中所做的一個示例。我有一個應用程序擁有自己的電子郵件帳戶,當他們填寫表單並按下提交按鈕時,會向用戶發送電子郵件。
重要請確保您有libSMTP.jar文件在您的應用程序引用。我正在使用下面的代碼庫。這裏是正在使用的,採取從它,你想一下下面的代碼,希望這是有用的:
進口需要:
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
提交按鈕,使請求發送電子郵件
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//-- Submit saves data to sqlite db, but removed that portion for this demo...
//-- Executes an new task to send an automated email to user when they fill out a form...
new sendEmailTask().execute();
}
}
});
電子郵件任務要在單獨的線程預製:使用
private class sendEmailTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPostExecute(Void result)
{
}
@Override
protected void onPreExecute()
{
}
@SuppressLint("ParserError")
@Override
protected Void doInBackground(Void... params)
{
try {
//--Note the send format is as follows: send(from, to, subject line, body message)
send("[email protected]", "[email protected]", "Form Submitted", "You submitted the form.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
發送功能:
public void send(String from, String to, String subject, String text) throws IOException
{
SMTPClient client = new SMTPClient("UTF-8");
client.setDefaultTimeout(60 * 1000);
client.setRequireStartTLS(true); // requires STARTTLS
//client.setUseStartTLS(true); // tries STARTTLS, but falls back if not supported
client.setUseAuth(true); // use SMTP AUTH
//client.setAuthMechanisms(authMechanisms); // sets AUTH mechanisms e.g. LOGIN
client.connect("smtp.gmail.com", 587);
checkReply(client);
//--Note the following format is as follows: client.login("localhost", (...your email account being used to send email from...), (...your email accounts password ...));
client.login("localhost", "[email protected]", "...myAppName email account password...");
checkReply(client);
client.setSender(from);
checkReply(client);
client.addRecipient(to);
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null)
{
SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, subject);
writer.write(header.toString());
writer.write(text);
writer.close();
client.completePendingCommand();
checkReply(client);
}
client.logout();
client.disconnect();
}
檢查的回覆功能使用:
private void checkReply(SMTPClient sc) throws IOException
{
if (SMTPReply.isNegativeTransient(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Transient SMTP error " + sc.getReplyCode());
}
else if (SMTPReply.isNegativePermanent(sc.getReplyCode()))
{
sc.disconnect();
throw new IOException("Permanent SMTP error " + sc.getReplyCode());
}
}
你想送一個電子郵件程序 - 馬上?例如:用戶按下按鈕,自動電子郵件將從代碼發送給他們。或者你是否希望允許用戶使用那裏的Gmail應用程序發送電子郵件?例如:用戶點擊一個按鈕,gmail應用程序打開它們發送電子郵件? – cking24343 2013-03-11 18:05:58