在本文中,我们将发送一封电子邮件,其中包含精心设计的表单以显示与邮件一起发送的数据。
众所周知,对我们所有人来说,使用电子邮件已经变得十分必要和重要。有各种电子邮件服务提供商,例如Yahoo,Outlook,iCloud和Gmail等。这些技术巨头为每个用户提供免费的电子邮件服务。如果您使用互联网,则无法忽略它,因为每当您访问任何网站/应用程序以在线购买/销售产品时,都可以。首先,您必须在这些网站/应用程序上注册才能证明您在现实世界中的身份。
在本文中,我们将学习如何使用JavaMail API将Gmail收件箱中的电子邮件发送到指定的电子邮件地址。我们将发送常见的用户数据,例如用户名,电子邮件地址,手机号码。等等
因此,让我们开始吧。
步骤1
- 首先,创建空的android项目,并在根目录中创建名称为MailSender.java和JSSEProvider.java的Java类。
- 现在,我们需要将Java Mail API jar文件导入到我们的项目中。从此处下载jar文件,解压缩并将其粘贴到libs文件夹中。
- 如果您的项目无法识别您的库,请重新启动Android Studio。
- 右键单击app-> New-> Folder-> Assets Folder,创建资产文件夹。我们将HTML文件放在此处,以在Gmail上显示数据。
- 要发送电子邮件,您的应用将需要互联网连接,因此请在AndroidManifest.xml文件中声明此权限。
第2步
- 在MailSender.java类中创建一些实例变量
// change this host name accordinglyprivate String mailhost = "webmail.xyz.in";private String user;private String password;private Session session;Context context;private Multipart _multipart = new MimeMultipart();
- 现在,在MailSender.java文件中创建静态块以调用JSSEProvider.java类。JSSEProvider用于链接SSLContext,X509的KeyManagerFactory,X509的TrustManagerFactory和AndroidCAstore的修改版本。
static { Security.addProvider(new JSSEProvider());}
- 创建参数化的构造函数(传递上下文,“发件人电子邮件ID”和“密码”等)以初始化实例变量,并创建Properties类的对象以在构造函数内设置属性。在其中传递上下文,用户电子邮件ID和密码。看一下构造函数代码。
public MailSender(Context context,String user, String password) { this.user = user; this.password = password; this.context = context; 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);}
- 最后,创建用户定义的方法sendUserDetailWithImage()以将数据发送到邮件。下面的代码从assets文件夹中提取user_profile.html,将其转换为缓冲区,然后从缓冲区中读取它,最后将其转换为字符串对象,用实际的用户名替换关键字“ ”等等。请参阅完整的sendUserDetailWithImage()代码。
public synchronized void sendUserDetailWithImage(String subject, String body, String sender, String recipients,String username,String email,String mobile,String dob,String age,String address,String profilePic ) throws Exception { MimeMessage message = new MimeMessage(session); DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); message.setFrom(new InternetAddress("no-reply@astromyntra.in")); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setDataHandler(handler); BodyPart messageBodyPart = new MimeBodyPart(); InputStream is = context.getAssets().open("user_profile.html"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String str = new String(buffer); str =str.replace("$$headermessage$$","You have got a new user."); str=str.replace("$$username$$", username); str=str.replace("$$email$$", email); str=str.replace("$$mobile$$", mobile); str=str.replace("$$dob$$",dob); str=str.replace("$$age$$",age); str=str.replace("$$address$$", address); messageBodyPart.setContent(str,"text/html; charset=utf-8"); _multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(_multipart); if (recipients.indexOf(',') > 0) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); Transport.send(message); }
UserDataSender.java
看完整的MainSender.java代码
package com.emailsender;import android.content.Context;import java.io.InputStream;import java.security.Security;import java.util.Properties;import javax.activation.DataHandler;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.util.ByteArrayDataSource;public class MailSender extends javax.mail.Authenticator { // change this host name private String mailhost = "webmail.xyz.in"; private String user; private String password; private Session session; Context context; private Multipart _multipart = new MimeMultipart(); static { Security.addProvider(new JSSEProvider()); } public MailSender(Context context,String user, String password) { this.user = user; this.password = password; this.context = context; 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 sendUserDetailWithImage(String subject, String body, String sender, String recipients,String username,String email,String mobile,String dob,String age,String address,String profilePic ) throws Exception { MimeMessage message = new MimeMessage(session); DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); message.setFrom(new InternetAddress("no-reply@xyz.in")); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setDataHandler(handler); BodyPart messageBodyPart = new MimeBodyPart(); InputStream is = context.getAssets().open("user_profile.html"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String str = new String(buffer); str =str.replace("$$headermessage$$","You have got a new user."); str=str.replace("$$username$$", username); str=str.replace("$$email$$", email); str=str.replace("$$mobile$$", mobile); str=str.replace("$$dob$$",dob); str=str.replace("$$age$$",age); str=str.replace("$$address$$", address); messageBodyPart.setContent(str,"text/html; charset=utf-8"); _multipart.addBodyPart(messageBodyPart); message.setContent(_multipart); if (recipients.indexOf(',') > 0) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); Transport.send(message); }}
MailSender.java
第三步
要在表单中显示数据,请在assets文件夹内创建名为user_profile.html的HTML文件,然后粘贴以下代码。
Dear Admin,
$$headermessage$$
Fields Details Username $$username$$ Email $$email$$ Mobile No. $$mobile$$ Age $$age$$ Dob $$dob$$ Address $$address$$
user_profile.html
HTML代码的输出看起来像这样
第四步
最后,将以下代码粘贴到您的MainActivity中。
package com.emailsender;import androidx.appcompat.app.AppCompatActivity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void sendMail(View view) { new MailCreator().execute(""); } public class MailCreator extends AsyncTask { @Override protected String doInBackground(String... strings) { try { MailSender sender = new MailSender(getBaseContext(), AppsConstants.SENDER_EMAIL,AppsConstants.SENDER_PASSWORD); sender.sendUserDetailWithImage("New User Added", "Hi", "Himanshu", AppsConstants.RECIPEINT_MAIL, "Himanshu Verma", "xyz@gmail.com", "+91 6075959010", "02/02/1994", "25","New Delhi, India",""); } catch (Exception e) { Log.e("SendMail", e.getMessage(), e); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s);// Toast.makeText(getActivity(),"Mail Sent",Toast.LENGTH_LONG).show(); } }}
MainActivity.java
结果
Data received on Gmail
注意:如果一切都很好,但仍然没有收到电子邮件,请检查您的垃圾邮件文件夹,如果该电子邮件位于此处,请单击“标记为非垃圾邮件”。
结论
我创建了一个Android项目,以电子邮件形式发送用户数据。我已经使用JavaMail API发送电子邮件。在本文中,我发送了HTML表单和数据。
如果您对本文有任何疑问或疑问,请随时在评论部分询问我。另外,您可以在我的Github帐户上找到本文的完整源代码。
翻译自:https://towardsdatascience.com/send-email-with-beautiful-form-in-android-b12cd5cc9572