send mail through java : multiple sender with different mail id - java

I want to send one mail to specified recipient but my sender can have different mail account like outlook or ymail or gmail.
Is it possible to send an email from different email id to same recipient? I'm using this code :
try
{final String from=request.getParameter("from");String smtpServ="",port="";final String pass=request.getParameter("pass");String to=request.getParameter("to");String subject=request.getParameter("subject");String body=request.getParameter("msg");if(from.contains("#gmail.com")){smtpServ="smtp.gmail.com";port="465";}else if(from.contains("#outlook.com") || from.contains("#hotmail.com")){smtpServ="smtp.live.com";port="587";}else if(from.contains("#ymail.com") || from.contains("#yahoo.com") || from.contains("#rocketmail.com") || from.contains("#yahoo.in")){smtpServ="smtp.mail.yahoo.com";port="465";}Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host",smtpServ);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
Session session1 = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,pass);
}
});Message message = new MimeMessage(session1);message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
message.setSubject(subject);
message.setText(body);
// -- Set some other header information --
message.setHeader("MyMail", "Java Mail Test");
message.setSentDate(new Date());Transport.send(message);System.out.println("Message sent to"+to+" OK."); }
catch (Exception ex)
{ ex.printStackTrace();System.out.println("Exception "+ex); }

Sending mails via Java (using Java Mail API) requires you to setup an SMTP host that would send your email to the recipient after proper log-in validation. I've used Java Mail with Gmail IDs and Gmail as SMTP host server. Some e-mail service providers do not allow sending emails from outside of their own web-services (making them incompatible with Java Mail).
But, in order to support multiple senders, you'll need to do the following:
Change the SMTP server to your correct host as per the email ID in use.
Run the Authenticator, with the new e-mail address and password, every time the sender ID is changed.
Then send your message.
My suggestion would be to store these sender email IDs and passwords (and SMTP hosts) when the program is initially run and then iterate the above steps with required changes, for each email id and password pair.
The Caveat:
In my opinion it's best to stick with a single sender else, multiple messages with similar content, by varied sender addresses, may be marked down as Spam by the recipients email service provider.

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
replace this thing with,
message.setRecipients(Message.RecipientType.TO, Address[] addresses);
[N.B.- addresses are ur desired IDs.]

Related

SMTP Mail Sending Issue : com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay

I am trying to send mail from Java.
If i will send mail to same SMTP it working fine.
If i will send mail to outside SMTP means like Gmail, Yahoo etc. it'as shows error like,
[com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay][1]
ERROR :
SimpleEmail Start
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
Mail Send Successfully
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at com.nirav.java.project.demo.JavaMailSend.sendEmail(JavaMailSend.java:26)
at com.nirav.java.project.demo.NewSimpleMail.main(NewSimpleMail.java:34)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1917)
... 5 more
Code For Mail Sending :
try {
System.out.println("SimpleEmail Start");
String smtpHostServer = "XX.XX.XX.XXX";
final String toEmail = "XXXXXXXXXX#XXX.XXX";
final String fromEmail = "XXXXXXXXXX#XXX.XXX";
final String password = "XXXXXXXXXXXX";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.port", "25"); //If other then
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
//Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.addHeader("format", "flowed");
message.addHeader("Content-Transfer-Encoding", "8bit");
message.setFrom(new InternetAddress("XXXXXX#XXX.XXX", "NoReply-JD"));
message.setReplyTo(InternetAddress.parse("XXXXXXXXX#XXX.XXX", false));
message.setSubject(subject, "UTF-8");
message.setText(body, "UTF-8");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
Transport.send(message);
System.out.println("Mail Send Successfully");
} catch (Exception e) {
e.printStackTrace();
}
Please help me.
Thnaks.
Originally I was about to post this as comment, but it's too long.
The error is quite obvious, you are not allowed to use given SMTP server as relay. (What are SMTP relays?)
There are couple of reasons why this can happen:
You are not authenticated (need to login before sending)
Recipient is not in list of domains allowed to relay to
IP address from which you are connecting is not in white list (aka mynetworks in postfix context)
without providing more info (which SMTP server you are using, where are you sending mail, are you authenticated), I guess nobody will help you.
5.7.1 status code from IANA registry
The sender is not authorized to send to the destination. This can be
the result of per-host or per-recipient filtering. This memo does not
discuss the merits of any such filtering, but provides a mechanism to
report such. This is useful only as a permanent error.
Had this problem also but it was intermittent.
We have 2 servers that are within a cluster and on one the ip address of system that sends the email was not defined correctly.
Unfortunately the error message "javax.mail.SendFailedException: Invalid Addresses is confusing.
the 2nd error message: "com.sun.mail.smtp.SMTPAddressFailedException: 550 relay not permitted" matches much better.

How to send an email from Outlook via Java?

I am stuck behind a corporate firewall that won't let me send email via conventional means such as Java Mail API or Apache Commons Email, even to other people inside the organization(which is all I want anyways). But my Outlook 2010 obviously can send these emails. I was wondering if there is a way to automate Outlook 2010 via Java code so that Outlook can send the emails ? I know stuff like "mailto" can be used pop-up the default Outlook send dialog with pre-populated info, but I am looking for a way to have the send operation happen behind the scenes. Thanks for any info.
You can send emails through outlook with javamail use the configurations described on Outlook's official site.
Here is small demo code
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public static void main(String[] args) {
final String username = "your email"; // like yourname#outlook.com
final String password = "*********"; // password here
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver mail")); // like inzi769#gmail.com
message.setSubject("Test");
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
.
Note: I tested this with Javamail API 1.5.6
I don't think there's any way to do what you want using Outlook.
Presumably your mail server is also behind the corporate firewall. If you're using Outlook for your client, you're probably using Exchange for your server. Exchange can be configured to support the standard SMTP protocol for sending mail, which would allow use of JavaMail. If you can't configure your Exchange server to support SMTP, you still might be able to use Exchange Web Services. If that doesn't work, you might need to use one of the JavaMail Third Party Products that supports the Microsoft proprietary mail protocol.
Process p = Runtime.getRuntime().exec("cmd /C start outlook ");

Send Java email without authentication (no such provider exception: smtp)

The code I am currently using is as follows:
String to = "....#gmail.com";
String from = ".....#gmail.com";
String host = "127.0.0.1";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
If I paste the above code in my Java servlet and run it, the following exception gets thrown:
javax.mail.NoSuchProviderException: smtp
I have also tried following the solutions outlined in these resources but to no avail: link1 link2 link3 link4.
It would help if you included the the full stacktrace for the javax.mail.NoSuchProviderException and JavaMail debug output. Because you are running this in a servlet container you could be running into Bug 6668 -skip unusable Store and Transport classes. Change your call to Transport.set to the following:
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
try {
Transport.send(message);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
That code will isolate which transport class the code is allowed to see. That will rule out that bug in your code.
NoSuchProviderException means something is messed up in your JavaMail API configuration. Where and how have you installed the JavaMail jar file?
Also, in case it's not clear from the other responses, the only way you're going to be able to send mail without authentication is if you're running your own mail server. You can't do it with general purpose online e-mail services (e.g. Gmail).
First of all, if you wanna use gmail to send emails from your program you need to define stmp host as gmail. Your current host "127.0.0.1" is localhost meaning your own computer? Do you have mail server running on your computer?
Here you can see some tutorial how to send an email using gmail: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you're afraid to pass your normal gmail account details then create some kind of test email like kselvatest or something.
You are missing pretty much those:
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
So basicly all you need to add is:
1.login and password so JavaMail can use some gmail account
2.declare which mail server you wanna use
change String host = "127.0.0.1"; to String host = "smtp.gmail.com";
3.set mail port
For this code you should get javax.mail.MessagingException: Could not connect to SMTP host: 127.0.0.1, port: 25; exception
But I suspect you have a jre issue. May be smtp implementation has a problem. Why don't you download java mail implementation from http://www.oracle.com/technetwork/java/javamail/index-138643.html and add it to your project class path and try?

Java mail going to Junk mail for distribution list group mail id

I am trying to send mail using Java mail to distribution list(group mail id) and its a success. but thing is its recieved in junk box in MS Outlook by default. How to make it been delivered to Inbox?
Mail from donotreply#.com should be delivered to Inbox.
String host = "SMARTHOST.XXXX.COM";
Properties prop = new Properties();
prop.load(PDFGenerator.propLoad());
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host); // smtp.gmail.com?
properties.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
// From e-mail Id
message.setFrom(new InternetAddress("donotreply#example.com"));
message.addRecipients(Message.RecipientType.TO, "groupmailId#example.com");
In outlook add the sender's email to the safe senders list. This has nothing to do with java, sendmail, etc... It has to do with a spam filter.

Sending email with google app engine

Im tring to send a simple email with this code using google app engine.
But nothing happens, is there something i have to configure in order to use the mail api?
This runs on localhost.
I am using gmail as mail host.
String host = "smtp.google.com";
String to = "example#yahoo.fr";
String from = "example#gmail.com";
String subject = "this is a test";
String messageText = "test";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
// Set debug on the Session
// Passing false will not echo debug info, and passing True will.
mailSession.setDebug(sessionDebug);
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
When running the AppEngine development server locally, anything sent via the Mail service will not actually be sent - it will just be logged to the console
See here
When an application running in the development server calls the Mail service to send an email message, the message is printed to the log. The Java development server does not send the email message.
In addition, the from address must be (from here)
The email of an app administrator
The email of the currently logged in user who signed in using a Google Account
A valid email receiving address from the app
The sender should be your own Gmail email address instead of example#gmail.com
Reason is because the SMTP server needs to authenticate you.
Apparently, GAE doesn't allow the use of the admin accounts any more. you need to use the service account: project-id#appspot.gserviceaccount.com
My previous projects still work with admin accounts, but the recently created projects just don't allow me to use any of the admin accounts.
Other than email not working on localhost or due to the sender email not being the authenticated one, I have experienced that email does not work even when the version is not the default one. I could not find this documented anywhere.
For example:
nondefaultversion-dot-myapp.appspot.com (email does not work, no error logs)
myapp.appspot.com (email works)
Please confirm if others have also faced this issue.

Categories