내 애플 리케이션에 텍스트 필드와 버튼이 있습니다. 나는 단지 사용자가 버튼을 누를 때 내 앱이 "Hello"텍스트가있는 이메일을 텍스트 필드의 방향으로 보내야합니다.프로그래밍 방식으로 간단한 이메일을 보내는 방법은 무엇입니까? (그것을 할 수있는 간단한 방법이 있습니까?)
쉬운 방법이 있나요?
내 애플 리케이션에 텍스트 필드와 버튼이 있습니다. 나는 단지 사용자가 버튼을 누를 때 내 앱이 "Hello"텍스트가있는 이메일을 텍스트 필드의 방향으로 보내야합니다.프로그래밍 방식으로 간단한 이메일을 보내는 방법은 무엇입니까? (그것을 할 수있는 간단한 방법이 있습니까?)
쉬운 방법이 있나요?
첫 번째 방법은입니다. 기본 전자 메일 프로그램이나 gmail 프로그램 (의도를 통함)에 연결하여 메일을 보내지 않고 전자 메일을 백그라운드에서 보내려는 경우 아래 코드를 참조하십시오.
이 도우미 클래스를 사용하여 필요에 맞게 조정할 수 있습니다.
MailService mailer = new MailService("[email protected]","[email protected]","Subject","TextBody", "<b>HtmlBody</b>", (Attachment) null);
try {
mailer.sendAuthenticated();
} catch (Exception e) {
Log.e(AskTingTing.APP, "Failed sending email.", e);
}
두 번째 방법 :
package com.myapp.android.model.service;
import android.util.Log;
import com.myapp.android.MyApp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
public class MailService {
// public static final String MAIL_SERVER = "localhost";
private String toList;
private String ccList;
private String bccList;
private String subject;
final private static String SMTP_SERVER = DataService
.getSetting(DataService.SETTING_SMTP_SERVER);
private String from;
private String txtBody;
private String htmlBody;
private String replyToList;
private ArrayList<Attachment> attachments;
private boolean authenticationRequired = false;
public MailService(String from, String toList, String subject, String txtBody, String htmlBody,
Attachment attachment) {
this.txtBody = txtBody;
this.htmlBody = htmlBody;
this.subject = subject;
this.from = from;
this.toList = toList;
this.ccList = null;
this.bccList = null;
this.replyToList = null;
this.authenticationRequired = true;
this.attachments = new ArrayList<Attachment>();
if (attachment != null) {
this.attachments.add(attachment);
}
}
public MailService(String from, String toList, String subject, String txtBody, String htmlBody,
ArrayList<Attachment> attachments) {
this.txtBody = txtBody;
this.htmlBody = htmlBody;
this.subject = subject;
this.from = from;
this.toList = toList;
this.ccList = null;
this.bccList = null;
this.replyToList = null;
this.authenticationRequired = true;
this.attachments = attachments == null ? new ArrayList<Attachment>()
: attachments;
}
public void sendAuthenticated() throws AddressException, MessagingException {
authenticationRequired = true;
send();
}
/**
* Send an e-mail
*
* @throws MessagingException
* @throws AddressException
*/
public void send() throws AddressException, MessagingException {
Properties props = new Properties();
// set the host smtp address
props.put("mail.smtp.host", SMTP_SERVER);
props.put("mail.user", from);
props.put("mail.smtp.starttls.enable", "true"); // needed for gmail
props.put("mail.smtp.auth", "true"); // needed for gmail
props.put("mail.smtp.port", "587"); // gmail smtp port
/*Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "mypassword");
}
};*/
Session session;
if (authenticationRequired) {
Authenticator auth = new SMTPAuthenticator();
props.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(props, auth);
} else {
session = Session.getDefaultInstance(props, null);
}
// get the default session
session.setDebug(true);
// create message
Message msg = new javax.mail.internet.MimeMessage(session);
// set from and to address
try {
msg.setFrom(new InternetAddress(from, from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)});
} catch (Exception e) {
msg.setFrom(new InternetAddress(from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
}
// set send date
msg.setSentDate(Calendar.getInstance().getTime());
// parse the recipients TO address
java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ",");
int numberOfRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients];
int i = 0;
while (st.hasMoreTokens()) {
addressTo[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);
// parse the replyTo addresses
if (replyToList != null && !"".equals(replyToList)) {
st = new java.util.StringTokenizer(replyToList, ",");
int numberOfReplyTos = st.countTokens();
javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos];
i = 0;
while (st.hasMoreTokens()) {
addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
st.nextToken());
}
msg.setReplyTo(addressReplyTo);
}
// parse the recipients CC address
if (ccList != null && !"".equals(ccList)) {
st = new java.util.StringTokenizer(ccList, ",");
int numberOfCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
}
// parse the recipients BCC address
if (bccList != null && !"".equals(bccList)) {
st = new java.util.StringTokenizer(bccList, ",");
int numberOfBCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressBCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC);
}
// set header
msg.addHeader("X-Mailer", "MyAppMailer");
msg.addHeader("Precedence", "bulk");
// setting the subject and content type
msg.setSubject(subject);
Multipart mp = new MimeMultipart("related");
// set body message
MimeBodyPart bodyMsg = new MimeBodyPart();
bodyMsg.setText(txtBody, "iso-8859-1");
if (attachments.size()>0) htmlBody = htmlBody.replaceAll("#filename#",attachments.get(0).getFilename());
if (htmlBody.indexOf("#header#")>=0) htmlBody = htmlBody.replaceAll("#header#",attachments.get(1).getFilename());
if (htmlBody.indexOf("#footer#")>=0) htmlBody = htmlBody.replaceAll("#footer#",attachments.get(2).getFilename());
bodyMsg.setContent(htmlBody, "text/html");
mp.addBodyPart(bodyMsg);
// set attachements if any
if (attachments != null && attachments.size() > 0) {
for (i = 0; i < attachments.size(); i++) {
Attachment a = attachments.get(i);
BodyPart att = new MimeBodyPart();
att.setDataHandler(new DataHandler(a.getDataSource()));
att.setFileName(a.getFilename());
att.setHeader("Content-ID", "<" + a.getFilename() + ">");
mp.addBodyPart(att);
}
}
msg.setContent(mp);
// send it
try {
javax.mail.Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP
* server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = DataService
.getSetting(DataService.SETTING_SMTP_USER);
String password = DataService
.getSetting(DataService.SETTING_SMTP_PASSWORD);
return new PasswordAuthentication(username, password);
}
}
public String getToList() {
return toList;
}
public void setToList(String toList) {
this.toList = toList;
}
public String getCcList() {
return ccList;
}
public void setCcList(String ccList) {
this.ccList = ccList;
}
public String getBccList() {
return bccList;
}
public void setBccList(String bccList) {
this.bccList = bccList;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setFrom(String from) {
this.from = from;
}
public void setTxtBody(String body) {
this.txtBody = body;
}
public void setHtmlBody(String body) {
this.htmlBody = body;
}
public String getReplyToList() {
return replyToList;
}
public void setReplyToList(String replyToList) {
this.replyToList = replyToList;
}
public boolean isAuthenticationRequired() {
return authenticationRequired;
}
public void setAuthenticationRequired(boolean authenticationRequired) {
this.authenticationRequired = authenticationRequired;
}
}
그리고이 클래스를 사용합니다. 메일을 보내기 위해 Android에서 기본 이메일 클라이언트 또는 Gmail을 사용하는 데 신경 쓸 필요가없는 다른 옵션 (사용자가 이메일 클라이언트에서 보내기 버튼을 실제로 누르지 않아도 됨)은 다음과 같이 할 수 있습니다.
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:[email protected]")));
public class MainActivity extends Activity
{
private static final String username = "emailaddress";
private static final String password = "password";
private EditText emailEdit;
private EditText subjectEdit;
private EditText messageEdit;
private Multipart _multipart;
@SuppressLint("SdCardPath")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailEdit = (EditText) findViewById(R.id.email);
subjectEdit = (EditText) findViewById(R.id.subject);
messageEdit = (EditText) findViewById(R.id.message);
Button sendButton = (Button) findViewById(R.id.send);
sendButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String email = emailEdit.getText().toString();
String subject = subjectEdit.getText().toString();
String message = messageEdit.getText().toString();
sendMail(email, subject, message);
}
});
}
private void sendMail(String email, String subject, String messageBody)
{
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]", "Tiemen Schut"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
private class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
@Override
protected Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
}
libs 폴더에 세 개의 jar 파일을 추가하고 시도하십시오. Mail.jar!
activation.jar!
additional.jar!
제목이나 본문을 직접 작성하고 edittext를 삭제하면 앱에서 직접 이메일을 전송합니다.
그리고 매니페스트
제출 귀하의 코드이 줄을 추가 버튼, 인터넷 권한을 부여하는 것을 잊지 마세요
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String\[\]{ "[email protected]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello There");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Add Message here");
emailIntent.setType("message/rfc822");
try {
startActivity(Intent.createChooser(emailIntent,
"Send email using..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(),
"No email clients installed.",
Toast.LENGTH_SHORT).show();
}
}
});
안드로이드가 자동으로 장치에 기한 클라이언트를 선택하고 사용자가 무료입니다
어떤 이메일 클라이언트를 선택하는 그는
한다고 가정 사용자가 메일 클라이언트로 Gmail을 선택합니다 내가 t는 다음과 같이 보일 것이다 : -이 방법
플러스 포인트가 조치를 선택하는 앱 & givinguser 자유에 여분의 항아리를 추가하지 않는 것입니다.
한 가지 더, 나는이 사이트의 다양한 대답에서 주어진 접근법을 사용했지만 단순히 작동하지 않습니다. 첫 번째 문제는 방화벽이었다 Transport.send(message)
는 다음과 같은 예외를 던지고 :
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketTimeoutException: failed to connect to smtp.gmail.com/64.233.184.108 (port 465) after 90000ms
를이 다음 방화벽을 차단하고 발생합니다. 다른 네트워크를 사용해보십시오.
네트워크를 전환 한 후 보안이 취약한 응용 프로그램에서 내 계정을 사용하려했음을 알리는 이메일이 Google로부터 전송되었습니다.
해결책은 덜 안전한 응용 프로그램을 위해 Gmail 액세스를 가능하게하는 것이 었습니다. 이 안드로이드 1.5 및 1.6와 호환되지 않습니다 ... 수입에
나는 많은 오류를 가지고이이 링크를 할 수 있는가? – NullPointerException
Android의 lib 폴더에 javax mail의 activation.jar/mail.jar을 추가해야합니다. 또한 1.6에서 작동해야합니다. –
어떻게 추가 하시겠습니까 ??? – NullPointerException