In googel app engine, if we are not using OpenID login, we can send mails like its written in API
But I use OpenId Login (using Google mail) and I cant use this.
But I do something like thatL
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(
"mail#gmail.com", "pass");
}
});
**Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mail"));
message.setSubject("Testing Subject");
message.setText(msgBody);
Transport.send(message);
IF I WILL LOG IN AND THEN CALL THAT SERVLET, for instance www.example.appspot.com/mail it works! but if I'm not logged in, it does not work!
But I don't understand what happens?!**
java.lang.RuntimeException: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Illegal Arguments (java.lang.IllegalArgumentException: Unauthorized Sender: Unauthorized sender))
at test.queue.MailServlet.sendMail(MailServlet.java:208)
at this 208 line I have this:
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("example#gmail.com","pass");
}
the address set in the "from" should be present under the Admission -> Permissions for the gae application, and for sending email from this permitted account, no need to specify password in the code.
"For security purposes, the sender address of a message must be the email address of an administrator for the application or any valid email receiving address for the app (see Receiving Mail). The sender can also be the Google Account email address of the current user who is signed in, if the user's account is a Gmail account or is on a domain managed by Google Apps." - as mentioned here https://developers.google.com/appengine/docs/java/mail/#Java_Sending_mail_with_the_JavaMail_API
Related
Business Requirement
OneDrive to have a user level folder created and shared to specific members of team.
Owning user to create folders for project and assign exclusive permissions to certain members (remove access to non-project members)
Technical Environment
One Drive access via Graph API
ADAL Auth
Web Job hosted as NativeJob in Azure App and granted required OneDrive access.
App registered in mine (not the account used to access OneDrive)
Current Effort
Since web-api & web apps cannot use username/password auth, required to access a specific user's drive, resorted to WebJob (not sure if it complies as native app).
WebJob tries to auth using the drive owner's credential but fails with message (AADSTS65001: The user or administrator has not consented to use the application with ID '<appId>' named 'OneDriveFileSystem'. Send an interactive authorization request for this user and resource.)
Code
Auth Request
UserCredential uc = new UserPasswordCredential(userName, password);
AuthenticationResult result = null;
try
{
var authContext = new AuthenticationContext(authority);
result = authContext.AcquireTokenAsync(resource, clientId, uc).Result;
}
catch (Exception ee)
{
return string.Empty;
}
return result.AccessToken;
OneDriveAccess
string accessToken = GetAuthToken();
if (!string.IsNullOrEmpty(accessToken))
{
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
string payload = "{ \"name\": \"" + projectRequest.ProjectName + "\" , \"folder\": { } }";
HttpContent content = new StringContent(payload,
System.Text.Encoding.UTF8,
"application/json");
Uri uri = new Uri(resource + "/v1.0" + RootFolderItemId + RootFolderItemId + "/children");
HttpResponseMessage response = httpClient.PostAsync(uri, content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
}
}
(results in 404, however same url works in Graph Explorer)
Question
Is this design correct or am I missing some critical element?
Do I need to register the app in the account which is used for OneDrive access or can it be allowed to register in any user's account as long as the keys are correct?
If I update the code to use my credential, it asks for multi-factor auth (enabled by admin), but since this is native, this cannot be provided. The drive owner account was created as a service one, so MFA is not applicable to that.
Any other code/configuration required can be provided
Update 1
Using the "me" based endpoint (to default to self's folder) results in a 403 Forbidden, even though I am sending a valid access token. Have granted all permissions for file access (see attached image). The Grant Permission is successful for all demanded permissions.
I try to connect from my App (Spring Boot application) to Gmail API in order to download some of my mail. It actually works, but I have a problem with authorization. When I call authorize() method, it gives me a auth link in IDE console. Is there any way to redirect user to authorization page instead of print this link in console?
My code:
public Credential authorize() throws IOException
{
InputStream inputStream = GTD.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(inputStream));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
public Gmail getGmailService() throws IOException
{
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("GTD")
.build();
}
EDIT: When I call functions from normal Java App, not web application, it works.
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
com.sun.mail.smtp.SMTPSendFailedException: 551 This mail server requires authentication before sending mail from a locally hosted domain. Please reconfigure your mail client to authenticate before sending mail.
I am getting the error above when I integrate with the my Java Application running on a Tomcat server
Sending successfully if I use the same properties in separate class with main and run as java application
Why I am not getting this? Thank you in advance.
Finally got answer
Here we go: before it was like
`Properties props = new Properties();
props.put("mail.smtp.host", "webmail.technobbyte.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);`
now i changed to:
`Properties props = new Properties();
props.setProperty("mail.smtp.host", "webmail.technobbyte.com");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.auth", "true");`
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.