I try to send email with Intent. I wrote code witch can send email
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { Email });
email.putExtra(Intent.EXTRA_SUBJECT,"subject");
email.putExtra(Intent.EXTRA_TEXT, "text1");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
}
});
I can send email, but when I choose email client then I can change subject text and extra text. How I can write code to use would not can change subject and extra texts when user would choose email client?
The only way to avoid the user from changing email text is to issue the mail
programmatically, i.e. with no UI. It is usually done in Android by using the JavaMail API.
Send Email via JavaMail
First add lines below to your sender class:
static {
Security.addProvider(new JSSEProvider());
}
JSSEP stands for Java Secure Socket Extension, which is the protocol used for
Gmail authentication that we will later on use.
You can grab a working sample of JSSEProvider at:
https://android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
Create a sender class :
public class EmailSender extends javax.mail.Authenticator {
void sendMail(username, password, ) {
...
}
}
We now move to sendMail() method implementation:
Start by setting properties for transmission via Gmail:
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com"); // <--------- via Gmail
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);
And follow by sending the mail:
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);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
ByteArrayDataSource is a standard implementation. You can grab it from
http://commons.apache.org/proper/commons-email/apidocs/src-html/org/apache/commons/mail/ByteArrayDataSource.html
You wil also need to add the method below, returning the PasswordAuthentication, to your class:
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
Good luck.
If you really need to lock in the subject and message body, but let the user choose the email recipients (the To list), you'll have to provide them a dialog to enter in email recipient, and then send the email in an automated fashion by using something like Apache Commons EMail
As a user, I'd be pretty wary of having an email sent from my phone where I can't see the subject line and body text. You may want to just use the method you have now wehre they can edit the text, or at least show them what you're sending.
Related
I have a simple web application where different users can log into it. One of the important feature is user can access a document and send email of it's content to an outsider like third party. Below is just how the email looks like to give an idea:
It's pretty self explanatory and I can send to multiple user if I want like abc#example.com,efg#hotmail.com,... in the field box shown.With all this, I am using Java Mail API to make it work and after hitting the send button,it sends directly to the recipient.No issue at all.
Now, I want to modify this by doing this email feature as a service.What this means is when I send the email,the content and info filled in will be stored in a table in MYSQL and the service(running in background) will pick up from the table and do the sending.
This is my function:
public void sendEmail(String recipient, String subject, String content,
String host, String port, final String senderaddress,
final String password) {
try {
System.out.println("Please Wait, sending email...");
/*Setup mail server */
Properties props = new Properties();
props.put("mail.smtp.host", host); //SMTP Host
props.put("mail.smtp.port", port); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderaddress, password);
}
};
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(senderaddress));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(content);
try {
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Can this be done in the way I want because I am unsure how to make it work?
1 ) After hitting Sending mail button from UI, You need to call a method for saving data like recipient, subject, content in DB
2)Write an email sender Service which retrieves non_delivered / pending mail from DB table and send it through Java Mail API
3)Scheduled email sender service with the help of ScheduledExecutorService
public static void sendEmail(String msgHeader, String msg, String emailId, String emailFrom) {
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.port", port#);
props.put("mail.smtp.auth.mechanisms", "NTLM");
props.put("mail.smtp.auth.ntlm.domain", domainName);
Session session = Session.getDefaultInstance(props, null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailFrom));
to = emailId;
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(msgHeader);
message.setText(msg, "utf-8", "html");
message.saveChanges();
session.getDebug();
Transport.send(message);
// Copy message to "Sent Items" folder as read
Store store = session.getStore("ntlm");
store.connect(mailServer, emailFrom, pwd);
Folder folder = store.getFolder("Sent Items");
folder.open(Folder.READ_WRITE);
message.setFlag(Flag.SEEN, true);
folder.appendMessages(new Message[] {message});
store.close();
} catch (Exception ex) {
logger.error("Error occured while sending Email !", ex);
}
}
When I try to execute the code above, i am able to send out the emails. the issue is with saving the email. I get an error (NoSuchProviderException) at the line
Store store = session.getStore("ntlm");
I have a few questions on this:-
The email sending part works without password verification with ntlm. Is it possible to save the sent email into the sent items folder without password verification. If yes then how?
session.getStore doesnt work when i use
a. smtp - exception (Invalid provider)
b. ntlm - exception (NoSuchProviderException)
what should i use here.
Thanks in advance for your help.
"ntlm" is not a type of Store, it's an authentication mechanism. The store types supported by JavaMail are "imap" and "pop3". You almost certainly want "imap". Just like sending, you're going to need to supply your username and password when connecting to your imap server.
Also, upgrade to the current version of JavaMail if possible.
I have a program where I have a number of users which each could be sending emails from different email accounts.
When I try to use JavaMail to send emails. They always get sent out by the account of the user who sent an email first.
user1 = new User("dummy-email#gmail.com", "dumpass12");
user2 = new User("second-dummy#gmail.com", "secondpass12");
user1.sendMail(toAddress, subject, body);
user2.sendMail(toAddress, subject, body);
Now when I do something like this, the second user will send a message but it will come from the SAME mailbox as user1 (i.e. both messages will come from dummy-email#gmail.com).
Can somebody explain to me why this is happening? Do I have to close the connection somehow? How can I send the two emails and have them come from the different accounts? Please help me.
Here is my code which actually sends the email connecting to the user's gmail account.
public void sendMail(String toAddress, String subject, String body){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(getUsername(),getPassword()); }
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getUsername()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Replace Session.getDefaultInstance() with Session.getInstance(). To understand why, read the javadocs for those methods carefully.
The following is the program, which I am trying to send e-mail. The code is error free and I don't get any run time exception. But the code is unable to send e-mail. I have revised this code a lot but can't get what is actually wrong.
The sender and the receiver both have GMail accounts. The sender has 2-step verification process disabled. (I don't think it matters for the receiver. Does it?)
The code :
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
class tester {
public static void main(String args[]) {
Properties props = new Properties();
props.put("mail.smtp.host" , "smtp.gmail.com");
props.put("mail.stmp.user" , "username"); // username or complete address ! Have tried both
Session session = Session.getDefaultInstance( props , null);
String to = "me#gmail.com";
String from = "from#gmail.com";
String subject = "Testing...";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO , new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Working fine..!");
System.out.println("fine!!??");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
Well, your code doesn't actually attempt to send the message. Take a look at Transport.send.
Here are some examples:
http://www.javapractices.com/topic/TopicAction.do?Id=144
http://www.vipan.com/htdocs/javamail.html
First of all, you forgot to call Transport.send() to send your MimeMessage.
Secondly, GMail needs to be configured to use TLS or SSL connection. The following needs to be added to your Properties (props):
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//To use SSL
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
To connect to GMail SMTP, use the Transport.connect() method. I see you are not using any Transport at all in your code, so add this:
Transport transport = session.getTransport();
//Connect to GMail
transport.connect("smtp.gmail.com", 465, "USERNAME_HERE", "PASSWORD_HERE");
transport.send(msg);
Alternatively, you can create a Session by including a javax.mail.Authenticator as a parameter.
Example:
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("USERNAME_HERE", "PASSWORD_HERE");
}
});
I hope this helps you.
Resources:
Send email with SMTPS (eg. Google GMail) (Javamail)
JavaMail API – Sending email via Gmail SMTP example
I am writing a simple Java program to send mail, but am getting errors. Here's the code:
package mypackage;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// Send a simple, single part, text/plain e-mail
public class Sendmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "atul.krbhatia#gmail.com";
String from = "atul.krbhatia#gmail.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.gmail.com";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiatee a message
Message msg = new MimeMessage(session);
System.out.println("in try blk");
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
System.out.println("in catch block");
mex.printStackTrace();
}
}
}//End of class
Here's the errors:
221 2.0.0 closing connection d1sm3094152pbj.24
in catch block
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. d1sm3094152pbj.24
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at mypackage.Sendmail.main(Sendmail.java:48)
Gmail only supports SMTP over SSL/TLS.
Add
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You also need to login to the server:
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
A simple google search for "javamail gmail" will yield many example of how to use JavaMail with GMail, like this one. Google also has a configuration page listing the connection configuration that you'll need so you can double check the settings.
This URL May help:
http://sbtourist.blogspot.com/2007/10/javamail-and-gmail-its-all-about.html
It looks like the server is expecting SSL. There are several other questions on here where people are also trying to send mail through Gmail using Java, I recommend taking a look at them.
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
Must issue a STARTTLS command first. Sending email with Java and Google Apps