I am trying to use the Appengine Mail API to send mail from my application. I'm running the code below which executes fine without exceptions but no mail is actually sent. Here's the code:
public static void sendNotificationEmail(String subject, String message, String emailAddress) {
System.err.println("Sending mail: " + emailAddress);
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("a#b.com", "Name"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
msg.setSubject(subject);
msg.setText(message);
Transport.send(msg);
System.err.println("done");
}
catch (Exception e) {
System.err.println(e);
}
}
a#b.com is a registered owner of the app (but not the billing administrator). Looking at the logs, "done" is printed but no email is sent.
Any ideas?
UPDATE:
Found out the emails are actually getting through but are in the spam folder. Any way to give my app more (reputation) to not be marked as spam. Our app sends out notification emails to users when something has changed in the system.
Maybe you email marked as spam because it was sent from different host, I mean that maybe it's not GMail-connected domain.
At this case, to prevent it from being marked as spam, it's very helpful to configure SPF for your domain, see google help: Creating an SPF record. It has helped me some time ago
Related
I need to send email from java program. I am first trying to understand basics. I found a snippet at:
https://www.javatpoint.com/example-of-sending-email-using-java-mail-api
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args){
String to = "sonoojaiswal1988#gmail.com";//change accordingly
String from = "sonoojaiswal1987#gmail.com";change accordingly
String host = "localhost";//or IP address
//Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
//compose the message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
}catch (MessagingException mex) {mex.printStackTrace();}
}
}
My question is that as per the code, it looks like anyone can use any sender email address string and send infinite emails to any receiver email address. I am missing something in my understanding, which will prevent such scenario to happen. Please help.
I understand that this is not a programming question, but guess, it will not take too much time to answer this basic question and don't know any other equally active forum.
This example works for servers which don't need authentication. And this is usually not applicable to the smtp servers used in production. Such servers are used mostly for testing purposes where they are not exposed over the internet. Hence, although its possible to send infinite number of mails as mentioned by you, no one would be interested in doing the same.
For the servers where authentication is necessary, credentials need to be provided. And this is explained in detail in the blog mentioned by you.
I have a Spring Boot application that sends emails. For any action that requires notification, a Mail instance is created with status PENDING in the database and a job is run to send the pending emails every minute. The status of the Mail instances are set as PENDING, SENT or FAILED.
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.from", myEmailAddress);
props.put("mail.smtp.timeout", 2000);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
MimeMessage message = new MimeMessage(session);
MimeMultipart content = getContent(mail, message, username);
message.setContent(content);
Transport.send(message);
mail.setStatus(MailStatus.SENT);
mailService.save(mail);
} catch (MailConnectException mce) {
mail.setStatus(MailStatus.FAILED);
mailService.save(mail);
} catch (Exception e) {
// other actions
}
Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like somerandomname#gmail.com, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the Transport.send(message); statement, the mail.setStatus(MailStatus.SENT); statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in myEmailAddress with content like the following:
The response from the remote server was: 550 5.1.1
somerandomname#gmail.com User unknown
Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the Mail instance to FAILED. What is the best way to achieve this?
If you use a service like AWS SES to send your mail, you can receive notifications about bounces (and complaints) either simply as notifications for a human to read, or as programmatic triggers that could be used to call an alert endpoint on your spring boot server, for example through AWS Lambda. There are other services that may be able to do the same, such as SendGrid.
Your Spring Boot application would have to retrieve the notifications (an email itself) from your inbox corresponding to the sender address of the initial email. There are various options how to achieve this:
Use a service with provides callbacks (triggers) for incoming messages as mentioned by Benjamin
Poll your inbox using a standard protocol like POP or IMAP
Hint for the second option: https://docs.spring.io/spring-integration/reference/html/mail.html#mail-inbound
Using Java, I can send email from a toy standalone class (with hard-coded data) perfectly fine, and I receive the email within seconds.
When the exact same code is called in the context of a servlet, however, the code executes without failure, but I don't actually receive the email.
How could that be? Is there something special about the servlet environment?
I'm running Tomcat 6, JRE 1.5.
Here is the code (I have edited my data):
public void sendEmail(String aSubject, String aBody){
Properties props = new Properties();
props.put("mail.host", "smtp.blah.ca");
props.put("mail.from", "from-blah#blah.ca");
Session session = Session.getDefaultInstance(props, null /*no authenticator*/);
System.out.println("JRE" + System.getProperty("java.version"));
System.out.println(session.getProperties());
MimeMessage message = new MimeMessage(session);
try {
message.addRecipient(
Message.RecipientType.TO, new InternetAddress("to-blah#blah.com")
);
message.setSubject(aSubject);
message.setText(aBody);
Transport.send(message);
}
catch (MessagingException ex){
System.err.println("Cannot send email. " + ex);
}
}
Edit: the email is recieved when the content (email body) is small. When the content is large, it's not recieved.
This is not java-related at all.
I tested a large email with a normal email client. The same behavior was seen: the email is sent fine, but I'm not receiving it in a timely manner, for some reason. (I haven't seen this kind of behavior before, but there it is...)
I am trying to send email using apache james but the emails are not getting delievered. Below is my code.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class test {
public static void main(String args[]) throws Exception {
String user = "test";
String password = "test";
String fromAddress = "test#localhost";
String toAddress = "test#gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.host", "localhost");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.username", user);
properties.put("mail.smtp.password", password);
properties.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(properties, null);
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject("Email from our JAMEs");
message.setText("hiiiiii!!");
Transport.send(message);
System.out.println("Email sent");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Also test user is added in apache james having password test. Requesting you to kindly help me out in the same.
I think problem caused by this:
Email servers before accepting any mail do a reverse dns query. They check the ip for domain that the email came from and the ip that email is really came from.
If ip of domain and ip of email sender does not match, mail servers think that email is junk or spam.
Here since your domain (localhost) is not a valid address when Email server send a reverse dns query does not get an IP and think your mail is junk or spam.
For more information check this: http://wiki.junkemailfilter.com/index.php/Fixing_Reverse_DNS
I faced the same problem. What I did:
Go to the path : \apps\james\conf
Open for edit the filename 'james-fetchmail.xml'
Change "fetchmail" from false to true as:
Restart the Apache James Server.
You would see the following messages printed on the console after you start the server:
James Mail Server 2.3.2
Remote Manager Service started plain:4555
POP3 Service started plain:110
SMTP Service started plain:25
NNTP Service started plain:119
FetchMail Started
Now, run your program. It should work!
Did you added the domain "localhost"?
If not, add the domain first, and after create the users.
$ james-cli AddDomain -h 127.0.0.1 localhost
check if domain exists
$ james-cli ListDomains -h 127.0.0.1
And, how do you started james? Using james.bat?
I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code:
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
// Get session
Session session = Session.getDefaultInstance(props, new Authenticator(){
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(m_sending_user, m_sending_pass);
}
});
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(m_sending_from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(vcea.get(i).emailaddr));
message.setSubject( replaceEnvVars(subject) );
message.setText(replaceEnvVars(body));
// Send message
try {
Transport.send(message);
} catch (Exception e){
Log.Error("Error sending e-mail to addr (%s): %s",
vcea.get(i).emailaddr, e.getLocalizedMessage() );
}
The issue is that the above code does work, sometimes. But for some e-mail addresses that I know to be valid (because I can send to them via a standard e-mail client), the above code will throw an "Invalid Address" exception when trying to send.
Any clues or hints would be greatly appreciated.
--Update: problem with authentication.
Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.
Not so when sending e-mail. You have to do a bit more. Add this:
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
props.put("mail.smtp.auth", "true");
which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:
Transport t = session.getTransport(m_sending_protocol);
t.connect(m_sending_user, m_sending_pass);
...
// Send message
try {
t.sendMessage(message, message.getAllRecipients());
} catch (Exception e){
Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.
Thanks for the clues to prompt me to look at the mail server side of things as well.
--Update: problem with authentication.
Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.
Not so when sending e-mail. You have to do a bit more. Add this:
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
props.put("mail.smtp.auth", "true");
which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:
Transport t = session.getTransport(m_sending_protocol);
t.connect(m_sending_user, m_sending_pass);
...
// Send message
try {
t.sendMessage(message, message.getAllRecipients());
} catch (Exception e){
Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.
Thanks for the clues to prompt me to look at the mail server side of things as well.
I would change the call to InternetAddress to use the "strict" interpretation and see if you get further errors on the addresses you are having trouble with.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(vcea.get(i).emailaddr, true ));
// ^^^^ turns on strict interpretation
Javadoc for InternetAddress constructor
If this fails, it will throw an AddressException which has a method called getPos() which returns the position of the failure (Javadoc)
A good hint for those using the ssl encryption in the smtp configuration, you should enable it by specifying the property mail.smtp.ssl.enable, as shown below:
props.put("mail.smtp.ssl.enable", "true");
Otherwise it can lead to similar problems as described above.
Try this:
String to="stackoverflow#so.com";
String cc="one#mail.com,two#mail.com"; //The separator ',' works good
message.setRecipients(Message.RecipientType.TO,new InternetAddress[] {
new InternetAddress(to) }); // This is only one mail
InternetAddress[] addr = parseAddressList(cc); //Here add all the rest of the mails
message.setRecipients(Message.RecipientType.CC,addr);
Sorry for my english. It's not good.
This seems to me like a problem that happened at my work.
If the code you are showing is being concurrent, then using directly System.getProperties
could be a problem, because the host value you put on them can be overwritten by next request, while still keeping the user and password from the overwritten host.
In our case, we solved that using a clone of the System.getProperties() hashtable.
Hope that helps (this problem was really hard to track).