I'm writing code for receive email and change into todo. I received fresh email and converted todo but I sent forward email or reply email app engine not receive the email. What's the problem. I used session and getdefaultinstance that's all rest of the code same as receive email code.please do the needful.thanks
IN SERVLET Properties props = new Properties();
Session email = Session.getDefaultInstance(props, null);
try
{
MimeMessage message = new MimeMessage(email,req.getInputStream());
String summary = message.getSubject();
String description = getText(message);
Address[] addresses = message.getFrom();
User user = new User(addresses[0].toString(), "gmail.com");
Date date =new Date();
DaoComments.INSTANCE.add(addresses[0].toString(),lid,date,description,"selcomment");
}catch (Exception e)
{ e.printStackTrace();
}
IN WEB.XML
EmailTicket
com.cloudnowtech.EmailAgentServlet
EmailTicket
/_ah/mail/*
IN appengine-web-app
mail
HERE I'M SENDING THE CODE. PLEASE CORRECT IT –
An important part of sending email is to, well, to send it. Perhaps you missed this part:
// Hand the message to the default transport service for delivery.
Transport.send(msg);
If you take a peek over on the right there ---->,
Wander the related questions for yourself and you should find some helpful tidbits.
Welcome to StackOverflow and have a nice day.
It looks like this:
I got answer. there is no setting for forward and reply email to receive. I declared field as String but reply or forward mail size as more than 500 character. so change as Text. now its working fine. thanks for all.
Thanks
Murugavel
Related
When I send an email using the Gmail API, recipients that are using the Gmail web interface are getting a phishing warning when they open the email.
However, when I send the exact same email content through the same Gmail account but using the web UI, the recipients do not get the phishing warning.
The only difference I can find between the two received emails, is that the one sent using the API has this additional header:
Received: from 114692869688 named unknown by gmailapi.google.com with HTTPREST; Tue, 11 Jun 2019 11:37:51 -0500
Does anyone know how to resolve this problem?
I have the same problem.
When defining your message does not define the from parameter :
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
#message['from'] = sender
message['subject'] = subject
encoded_message = urlsafe_b64encode(message.as_bytes())
return {'raw': encoded_message.decode()}
In fact, this parameter is also defined when giving the user_id to the send method.
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
In my case recipients get the emails ok, but senders got their own messages flagged as phishing in their sent messages tray.
After some time struggling with this, it seems a case-sensitive issue.
Once I capitalized the f in the "from" header the problem went away.
So:
# sender something like "John Doe <johndoe#gmail.com>"
message['From'] = sender
Make sure your from-header is ['From'], and not ['from'] (like Google's guide shows).
This one-line diff:
## -129,7 +129,7 ## def create_message(sender, to, subject, message_text):
"""
message = MIMEText(message_text)
message["To"] = to
- message["from"] = sender
+ message["From"] = sender
message["Subject"] = subject
return {"raw": base64.urlsafe_b64encode(message.as_bytes()).decode("ascii")}
Is the difference between getting this failure:
and this success:
There are two options:
Send an email through Gmail SMTP (Simple Mail Transfer Protocol, a protocol for sending e-mail messages between servers)
Authorizing Your App with Gmail - All requests to the Gmail API must be authorized by an authenticated user. Gmail uses the OAuth 2.0 protocol for authenticating a Google account and authorizing access to user data.
When you get an email that looks suspicious, here are a few things to check for:
Check that the email address and the sender name match.
Check if the email is authenticated.
Hover over any links before you click on them. If the URL of the link doesn't match the description of the link, it might be leading you to a phishing site.
Check the message headers to make sure the "from" header isn't showing an incorrect name.**
Yes, the message header is important when sending an email using Gmail API. You will need to trace an email with its full headers.
I want to email my customers using different "roles" (e.g. info# , customer-support#, tech-support#, no-reply#).
I've tried 2 approaches:
Multiple "users"/accounts in my Gmail for business application.
Single gmail
account with multiple aliases.
I started by setting up a Service Account with global delegation for my Gmail for Business application.
To test that it works, I've set up 2 users: lev#mydomain.com and root#mydomain.com. Indeed, I can successfully send email both from lev# and root#.
However, when I tried adding 5 distinct user accounts for my application, Gmail got paranoid of bots/abuse and asked me to prove that all the accounts are "human" including setting up passwords, signing in and SMS-text validation via phone. Moreover, they require different phones for different accounts to prove it's a different person. So the setup of the accounts becomes a major issue.
I also want to avoid creating multiple accounts since I'm paying for each one, and since semantically, all the roles are just a single account. So aliases seem like a better idea.
The problem is that when I'm trying to send email and set the "from" field to the alias (e.g. from:no-reply#mydomain.com), I'm getting the following exception:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Delegation denied for root#mydomain.com",
"reason" : "forbidden"
} ],
"message" : "Delegation denied for root#mydomain.com"
}
Anyone faced and solved this issue?
The authentication/credential code is as follows:
/*
* Set up a hashmap HashMap<String, Gmail> gmailServiceByAccount where
* gmailServiceByAccount.get(emailAccount) contains an authorized Gmail service
*/
private void prepareService(String emailAccount) throws Exception {
if (gmailServiceByAccount.containsKey(emailAccount)) {
return;
}
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(Config.getInstance().getProperty(Config.gmail_service_account))
.setServiceAccountPrivateKeyFromP12File(new File(Config.getInstance().getPathToGmailCredential()))
.setServiceAccountScopes(Arrays.asList(GmailScopes.GMAIL_COMPOSE))
.setServiceAccountUser(emailAccount)
.build();
gmailServiceByAccount.put(
emailAccount,
new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(Config.getInstance().getProperty(Config.google_client_api_application_name))
.build());
}
And the code which sends the email is as follows:
/**
* Send an email using the parameters provided.
*
* #param fromPersonalName : the free text description of the "from" address (e.g. "Customer Suppport" or "No Reply").
* #param fromAddress : the email address of the sender, the mailbox account (e.g. customer-support#mydomain.com).
* #param to : the email address of the recepient.
* #param subject : Subject of the email.
* #param htmlContent : (may be null) The HTML-styled body text of the email.
* #param plainTextContent : (may be null) The plain text body of the email (e.g if the customer email client does not support or disables html email).
*/
public void sendMail(String fromPersonalName, String fromAddress, String to, String subject, String htmlContent, String plainTextContent)
throws Exception {
prepareService(fromAddress);
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(fromAddress);
fAddress.setPersonal(fromPersonalName);
email.setFrom(fAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
Multipart multiPart = new MimeMultipart("alternative");
if (!StringValidation.isEmpty(plainTextContent)) {
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(plainTextContent, "text/plain");
textPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
multiPart.addBodyPart(textPart);
}
if (!StringValidation.isEmpty(htmlContent)) {
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html; charset=\"UTF-8\"");
multiPart.addBodyPart(htmlPart);
}
email.setContent(multiPart);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
gmailServiceByAccount.get(fromAddress).users().messages().send(fromAddress, message).execute();
}
After additional research, it looks like the only option is to have multiple users.
The code I've posted indeed works for multiple users, but not for anything else.
I've tried multiple options including aliases and group email accounts. I'd either get "delegation denied" or "invalid grant" errors.
I've tried contacting Google For Business customer and tech support, but they don't support the API.
There's a great workaround to creating several users without having to go through phone validation. Just specify these users as "existing users" when you're signing into Google For Business initially, and activate them before you even transfer the domain.
For the account I've created without pre-existing users, I had to ask my friend's phones for phone validation.
You can now send emails using aliases as long as those aliases are defined for the user whose login credentials you're using.
This works for the Gmail for business only.
Setting up aliases to non-existent address can be tricky, so have a look at this how to set up a catch-all routing:
catchall-for-domain-aliases-in-gsuite-gmail
Just additionally to Ladi's post, it seem to be easier to setup now. Make an alias account and configure it so you can send emails (https://support.google.com/domains/answer/9437157?hl=en&ref_topic=6293345) and set the 'from' field on the message to the alias (but still use 'me' on the API call)
Is there a way to change "from address" or email-id on email sent from Google App engine Code ? I am able to change the reply-to address but send-from mail address is only taking Administrator email id. Is there an application setting through which i can change the sent from email id ?
Message msg = new MimeMessage(session11);
msg.setFrom(new InternetAddress(Constants.DB.Connection.ADMINEMAIL, "TEST MAIL"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(useremail, " TEST MAIL"));
msg.setReplyTo(new javax.mail.Address[]
{
new javax.mail.internet.InternetAddress(" testemail#xyz.com")
});
msg.setSubject(subject);
msg.setContent(message,"text/html");
Transport.send(msg);
Any suggestion or help would be appreciated
Yes, you can change the sender. But, that email must be listed as an administrator (developer). Your app can have more than one administrator.
Does the required servlet URL mapping (/_ah/xmpp/message/chat/) for the xmpp service restrict me to using only that servlet for both sending and receiving xmpp messages?
My application receives messages, adds them to an 'inQueue' for processing, and once processed, the results are added to an 'outQueue'. Ideally I'd like the worker servlet assigned to the outQueue to send the response.
I am using push queues and the servlets are obviously invoked by an HTTP POST request...
When I try to use the xmpp service to send the message from my outQueue worker ( which is obviously not mapped to /_ah/xmpp/message/chat/ ), it expectedly does nothing.
In the servlet mapped to /_ah/xmpp/message/chat/:
//Generate a Memcache key
String key = generateMemcacheKey(message);
//Serialize the message as xml using getStanza (for now, just put in the senderJID as string)
String senderJIDString = message.getFromJid().getId();
//Cache the message in Memcache
cache.put(key, senderJIDString);
//Enqueue a task for the message
private Queue queue = QueueFactory.getQueue("inQueue");
queue.add(TaskOptions.Builder.withUrl("/xmppParser").param("memcacheKey", key));
In xmppParser servlet doPost method:
//Extract message from memcache
String key = req.getParameter("memcacheKey");
String recipientJIDString = (String)cache.get(key);
//Todo Detect language
//Todo Parse Message into an Imperative accordingly (For now, just reply hello)
//Todo Handle Session status
//Put Imperative into memcache (For now, just put recipientID in)
cache.put(key, recipientJIDString);
//Enqueue appropriately
Queue queue = QueueFactory.getQueue("outQueue");
queue.add(TaskOptions.Builder.withUrl("/responseServlet").param("memcacheKey", key
));
Now I would like this responseServlet to send the reply:
//Get a handler on the memcache
MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
//Extract the key to the response from the request
String key = req.getParameter("memcacheKey");
//Extract the message from the memcache ( For now it's just the JID of the sender)
String recipientJIDString = (String)cache.get(key);
//Parse it into a message (For now just make a simple "I hear you" message)
JID recipientJID = new JID(recipientJIDString);
Message response = new MessageBuilder()
.withMessageType(MessageType.NORMAL)
.withRecipientJids(recipientJID)
.withBody("I hear you")
.build();
//Send the message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
xmpp.sendMessage(response);
The servlet mappings are all kosher, and the xmpp service is unable to send the message. It raises a null pointer exception, but the memcache viewer confirms the recipientJID is kosher as well... I'm guessing only the servlet mapped to /_ah/xmpp/message/chat/ is able to send messages, or am I wrong?
I am forced to test on the live site itself as XMPP does not seem to be supported by the development server, adding the possibility of my having overlooked some production environment configuration...
Much obliged!
ram
I was trying a method to implement email notification Using JavaMail.I wrote the code and there is no error. But no email has been sent.
I am using GAE with JSF2.
Properties props = new Properties();
javax.mail.Session session1 = javax.mail.Session.getDefaultInstance(props, null);
String msgBody = "This is a test mail";
try {
System.out.println("Email notification is sending");
Message msg = new MimeMessage(session1);
msg.setFrom(new InternetAddress("myGmailId1#gmail.com", "Example.com Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress("myGmailId2#gmail.com", "Mr. User"));
msg.setSubject("Your Example.com account has been activated");
msg.setText(msgBody);
Transport.send(msg);
System.out.println("Email notification has been sent");
} catch (AddressException e) {
// ...
} catch (MessagingException e) {
// ...
}
Where I went wrong?
Check that your sender e-mail address either registered as the administrator of your app, or the e-mail address of the current user that's logged in to the app.
According to the App Engine Mail API documentation:
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.