I am using java mail api to send email and I need to know the parameters to use for sending a test email in development environment
If I want to use smtp.gmail.com as the smtp mail server , it has port 465 - found on internet , do I need to set authentication to true with username and password also set or authentication=false in fine?
also if authentication=true is required then username, password are my gmail username & password?
Also how to set the cc and bcc addresses in the email message?
Looking for the most basic way to send email to start with
Thanks
If you want to use Gmail, see the JavaMail FAQ.
In order to use gmail as your email server, you have to set a few properties like host,port,authentication etc as per JavaMail API standards. You can get these details from
https://support.google.com/a/answer/176600?hl=en
Sample Code:
public class SendMail
{
public SendMail()
{
// mail properties outgoing server (gmail.com)
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
//Create session object
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);
//prepare mail msg
MimeMessage msg = new MimeMessage(session);
//set header values
msg.setSubject("open to it know it1");
msg.setFrom(new InternetAddress("yyyyyy#gmail.com"));
//Here in below line, you can specify RecipientType as TO/CC/BCC as per your requirement
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("xxxxxxx#gmail.com"));
//msg text
msg.setText("mail from HCL Technlogies");
Transport.send(msg);
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("nitraja2015#gmail.com","raryan500");
}
This is not a programming question. Firstly, if you're on not an a dynamically-assigned IP address (that is likely spam-blocked by many mail servers), you don't need an SMTP server. You just take "toaddress#domain" and resolve the "domain" part to a mail exchange handler (DNS MX record lookup) make a direct SMTP connection to that server and put your mail there. You don't program this yourself because mail-handling applications or middleware should know how to do this all by itself.
If you're not on a clean static IP address, you probably can't do that because many SMTP servers will reject connections from such addresses (a common source of spam!).
In that case, your first solution is to relay through the SMTP server provided by your internet provider. (It may be secured, so you have to set up your authentication credentials.)
If that doesn't work (e.g. it is too insecure or otherwise spam-friendly and so widely black-listed) then you look elsewhere for SMTP sending solutions.
Nobody can answer this for you because the best SMTP server depends on how you are hooked up to the Internet.
Related
I am following code to send mail without authentication.The java code described as follows.
final String frommail = "a#g.com"
String toEmail = "b#gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", PropertiesLoader.getPropertiesValue(MAIL_SMTP_AUTH));
props.put("mail.smtp.host", PropertiesLoader.getPropertiesValue(MAIL_SMTP_HOST));
props.put("mail.smtp.port", PropertiesLoader.getPropertiesValue(MAIL_SMTP_PORT));
//enable authentication
props.put(MAIL_SMTP_ENABLE, PropertiesLoader.getPropertiesValue(MAIL_SMTP_ENABLE));
Session session = Session.getInstance(props);
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(frommail, EMAIL_FROM_NAME));
// msg.setReplyTo(InternetAddress.parse(frommail, false));
msg.setSubject(subject, "UTF-8");
msg.setContent(body, MAIL_CONTENT_TYPE);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("pramilkprince#rediffmail.com", false));
Transport.send(msg);
logger.info("EMail Sent Successfully!!");
But when sending mail, it throws following exception
com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1
: Relay access denied at
com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862) at
com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118)
at javax.mail.Transport.send0(Transport.java:254) at
javax.mail.Transport.send(Transport.java:124) at
com.gtl.gcc.util.SendEmail.sendEmailFromInfo(SendEmail.java:195) at
com.gtl.gcc.util.SendEmail.createMailBodyAndSendMailForUpdateKYC(SendEmail.java:144)
if any one have any idea about this please help
If you want to send mail without authentication, you need to run your own SMTP server. If it's on the public internet, it will be flooded with spam before you can use it yourself. If it's on your private intranet, you can make it work. Gmail, for example, is definitely not going to let you send mail without authenticating. Note that this has absolutely nothing at all to do with use of the JavaMail API.
As #BillShannon pointed out, sending through most SMTP servers will require authentication due to SPAM issues.
However, the MX Gateways for any domain are required to be open on TCP 25 and for emails without authentication.
While working on Java send email avoiding smtp relay server and send directly to MX server I created a small example to use the target domain's MX server to directly address that.
As pointed out before: If your sending server does not reverse-DNS to the domain you're sending from, you'll most likely end up being blocked or directly classified as spam.
Good Luck
I have been using java mail to send mail from jsp to send emails.
But google is blocking my request and I am getting a message from gmail to my inbox as Signin attempt blocked.
In order to send mails from my account I have to update my security setting access permission to less secureapps but I don't want to do it.
So how to send mails using ssl in java mail?
The sample code I am using is:
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
The "less secure apps" setting has nothing to do with SSL. It's required to allow you to login using just a username and password, instead of using the (more complicated, but presumably more secure) OAuth2 authentication technique.
I'm trying to connect to Microsoft Exchange server using Javamail. I have used IMAP protocol and port 443 is enabled to listen on exchange server side. I'm getting "javax.mail.MessagingException:Connection reset" error. I'm using javamail 1.4.7 Please help..
Properties prop = new Properties();
prop.setProperty("mail.imap.starttls.enable", "false");
// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");
// Use port 443
prop.setProperty("mail.imap.port", "443");
prop.setProperty("mail.imap.socketFactory.port", "443");
prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");
Session session = Session.getDefaultInstance(prop);
Store store = session.getStore("imaps");
store.connect(hostname,username, password);
Port 443 is the https port, not the imaps port.
If you want to use the standard IMAP-over-SSL port, just use the "imaps" protocol and let JavaMail use the default port.
Also, see the JavaMail FAQ for some common mistakes in your code.
Thanks a lot for your suggestions..Yes indeed it was problem with the port. As suggested, I modified my code as below and it works fine now.
Properties prop = new Properties();
//Use SSL
prop.setProperty("mail.smtp.ssl.enable",true);
Session session = Session.getInstance(prop);
Store store = session.getStore("imaps");
store.connect(hostname,username, password);
I am using JAMES (Java Apache Mail Enterprise Server) as a mail server, and i am aiming to develop an enterprise java mailing system using Java-mail and JAF APIs on a local mail server.
For instance, i have made a simple application for test, i used the pop3 protocol to send/receive messages between clients and everything was OK.
The problem which occurred is that i want to view the sent/ deleted/ trash emails for each client which is not available in pop3 protocol. I have to use IMAP in stead.
But actually, the connection to the server using IMAP protocol is not working !!
this is a sample of the code :
#Stateless
public class Mailer{
#Resource(name = "mail/JavaMailSession")
private Session session
private Message[] messages;
private Message [] outboxContent(String email,String pass){
IMAPStore store = null;
IMAPFolder outbox = null;
try{
store = (IMAPStore) session.getStore("imaps");
store.connect("localhost",-1,email,pass);
if(store.isConnected()){
outbox = (IMAPFolder) store.getFolder("sent-items");
.
.
.
The exception is being thrown at :
store.connect(....
The exception being thrown is :
java.mail.MessagingException : Connection refused : connect;
nested exception is :
java.net.ConnectionException: Connection refused : connect
Anybody has idea about the sollution ?
Thanks in advance
The API is a backend to a mobile app. I don't need user authentication. I simply need a way to secure access to this API. Currently, my backend is exposed.
The documentation seems to only talk about user authentication and authorization, which is not what I need here. I just need to ensure only my mobile app can talk to this backend and no one else.
Yes, you can do that: use authentication to secure your endpoints without doing user authentication.
I have found that this way of doing it is not well documented, and I haven't actually done it myself, but I intend to so I paid attention when I saw it being discussed on some of the IO13 videos (I think that's where I saw it):
Here's my understanding of what's involved:
Create a Google API project (though this doesn't really involve their API's, other than authentication itself).
Create OATH client ID's that are tied to your app via its package name and the SHA1 fingerprint of the certificate that you will sign the app with.
You will add these client ID's to the list of acceptable ID's for your endpoints. You will add the User parameter to your endpoints, but it will be null since no user is specified.
#ApiMethod(
name = "sendInfo",
clientIds = { Config.WEB_CLIENT_ID, Config.MY_APP_CLIENT_ID, Config.MY_DEBUG_CLIENT_ID },
audiences = { Config.WEB_CLIENT_ID }
// Yes, you specify a 'web' ID even if this isn't a Web client.
)
public void sendInfo(User user, Info greeting) {
There is some decent documentation about the above, here:
https://developers.google.com/appengine/docs/java/endpoints/auth
Your client app will specify these client ID's when formulating the endpoint service call. All the OATH details will get taken care of behind the scenes on your client device such that your client ID's are translated into authentication tokens.
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAccountCredential credential = GoogleAccountCredential.usingAudience( ctx, Config.WEB_CLIENT_ID );
//credential.setSelectedAccountName( user ); // not specify a user
Myendpoint.Builder builder = new Myendpoint.Builder( transport, jsonFactory, credential );
This client code is just my best guess - sorry. If anyone else has a reference for exactly what the client code should look like then I too would be interested.
I'm sorry to say that Google doesn't provide a solution for your problem (which is my problem too).
You can use their API key mechanism (see https://developers.google.com/console/help/new/#usingkeys), but there is a huge hole in this strategy courtesy of Google's own API explorer (see https://developers.google.com/apis-explorer/#p/), which is a great development tool to test API's, but exposes all Cloud Endpoint API's, not just Google's services API's. This means anyone with the name of your project can browse and call your API at their leisure since the API explorer circumvents the API key security.
I found a workaround (based on bossylobster's great response to this post: Simple Access API (Developer Key) with Google Cloud Endpoint (Python) ), which is to pass a request field that is not part of the message request definition in your client API, and then read it in your API server. If you don't find the undocumented field, you raise an unauthorized exception. This will plug the hole created by the API explorer.
In iOS (which I'm using for my app), you add a property to each request class (the ones created by Google's API generator tool) like so:
#property (copy) NSString *hiddenProperty;
and set its value to a key that you choose. In your server code (python in my case) you check for its existence and barf if you don't see it or its not set to the value that your server and client will agree on:
mykey,keytype = request.get_unrecognized_field_info('hiddenProperty')
if mykey != 'my_supersecret_key':
raise endpoints.UnauthorizedException('No, you dont!')
Hope this puts you on the right track
The documentation is only for the client. What I need is documentation
on how to provide Service Account functionality on the server side.
This could mean a couple of different things, but I'd like to address what I think the question is asking. If you only want your service account to access your service, then you can just add the service account's clientId to your #Api/#ApiMethod annotations, build a GoogleCredential, and invoke your service as you normally would. Specifically...
In the google developer's console, create a new service account. This will create a .p12 file which is automatically downloaded. This is used by the client in the documentation you linked to. If you can't keep the .p12 secure, then this isn't much more secure than a password. I'm guessing that's why this isn't explicitly laid out in the Cloud Endpoints documentation.
You add the CLIENT ID displayed in the google developer's console to the clientIds in your #Api or #ApiMethod annotation
import com.google.appengine.api.users.User
#ApiMethod(name = "doIt", scopes = { Constants.EMAIL_SCOPE },
clientIds = { "12345678901-12acg1ez8lf51spfl06lznd1dsasdfj.apps.googleusercontent.com" })
public void doIt(User user){ //by convention, add User parameter to existing params
// if no client id is passed or the oauth2 token doesn't
// match your clientId then user will be null and the dev server
// will print a warning message like this:
// WARNING: getCurrentUser: clientId 1234654321.apps.googleusercontent.com not allowed
//..
}
You build a client the same way you would with the unsecured version, the only difference being you create a GoogleCredential object to pass to your service's MyService.Builder.
HttpTransport httpTransport = new NetHttpTransport(); // or build AndroidHttpClient on Android however you wish
JsonFactory jsonFactory = new JacksonFactory();
// assuming you put the .p12 for your service acccount
// (from the developer's console) on the classpath;
// when you deploy you'll have to figure out where you are really
// going to put this and load it in the appropriate manner
URL url = getClass().class.getResource("/YOURAPP-b12345677654.p12");
File p12file = new File(url.toURI());
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder();
credentialBuilder.setTransport(httpTransport);
credentialBuilder.setJsonFactory(jsonFactory);
//NOTE: use service account EMAIL (not client id)
credentialBuilder.setServiceAccountId("12345678901-12acg1ez8lf51spfl06lznd1dsasdfj#developer.gserviceaccount.com"); credentialBuilder.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
credentialBuilder.setServiceAccountPrivateKeyFromP12File(p12file);
GoogleCredential credential = credentialBuilder.build();
Now invoke your generated client the same way
you would the unsecured version, except the builder takes
our google credential from above as the last argument
MyService.Builder builder = new MyService.Builder(httpTransport, jsonFactory, credential);
builder.setApplicationName("APP NAME");
builder.setRootUrl("http://localhost:8080/_ah/api");
final MyService service = builder.build();
// invoke service same as unsecured version