I am trying to send an email using java client api. No matter what I try, I get this json error:
{
"code": 403,
"errors": [
{
"domain": "global",
"message": "Invalid user id specified in request/Delegation denied",
"reason": "forbidden"
}
],
"message": "Invalid user id specified in request/Delegation denied"
}
Any ideas how to bypass this error??
The code relevant to the specific issue, creating a MIME message and then creating the according Message as needed:
#Path("/sendmessage/{to}/{from}/{subject}/{body}/{userID}")
#GET
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sendMessage(
#PathParam("to")String to,
#PathParam("from") String from,
#PathParam("subject") String subject,
#PathParam("body") String body,
#PathParam("userID") String userID)
{
MimeMessage mimeMessage =null;
Message message = null;
mimeMessage =createEmail(to, from, subject, body);
message = createMessageWithEmail(mimeMessage);
gmail.users().messages().send(userID,message).execute();
resp = Response.status(200).entity(message.toPrettyString()).build();
return resp;
}
public static MimeMessage createEmail(String to, String from, String subject, String bodyText){
Properties props = new Properties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "******");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage email = new MimeMessage(session);
try{
InternetAddress toAddress = new InternetAddress(to);
InternetAddress fromAddress = new InternetAddress(from);
email.setFrom(fromAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
email.setSubject(subject);
email.setText(bodyText);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, ********);
transport.sendMessage(email, email.getAllRecipients());
transport.close();
}
catch(Exception e){
LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());
}
return email;
}
public static Message createMessageWithEmail(MimeMessage email){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
email.writeTo(baos);
} catch (IOException | MessagingException e) {
LOGGER.error("Class: "+className+", Method: "+methodName+", "+e.getMessage());
}
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
Pass empty string or "me" as the userId in the Gmail API call:
gmail.users().messages().send("", message).execute();
please try this
public static boolean sendEmail(String subject,String to,String content, MultipartFile file,String filenameName) throws Exception{
try{
final String username = "***#gmail.com";
final String 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");// For gmail Only U can change as per requirement
props.put("mail.smtp.port", "587"); //Different port for different email provider
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
Message message = new MimeMessage(session);
message.setHeader("Content-Type","text/plain; charset=\"UTF-8\"");
message.setSentDate(new Date());
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
if(file!=null){
//-Multipart Message
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(content);
multipart.addBodyPart(messageBodyPart);//Text Part Add
// Part two is attachment
messageBodyPart= new MimeBodyPart() ;
ByteArrayDataSource source=new ByteArrayDataSource(file.getBytes(),"application/octet-stream");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
//Send the complete message parts
message.setContent(multipart);
}
else
message.setText(content);
//message.setText(content);
Transport.send(message);
}
catch(Exception e){
return false;
}
return true;
}
Generally this type of error occurs when authenticated email address and from email address miss match occurs.
So, if you are using client library then pass "me" or empty string while executing as shown in below
gmail.users().messages().send("me", message).execute();
if you are using rest api then use
https://www.googleapis.com/gmail/v1/users/me/messages
Related
I am writing an email client to send email using yahoo SMTP server.
Getting error: com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
Passed Authentication but throwing 554 while sending email:-
public static void main(String[] args) {
final String fromEmail = "myyahoo#yahoo.com"; //requires valid id
final String password = "xxxxxxx"; // correct password for gmail id
final String toEmail = "test.existing#gmail.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.mail.yahoo.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "Required"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
System.out.println("Calling getPasswordAuthentication");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
System.out.println("After getPasswordAuthentication");
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"My First TLSEmail Testing Subject", "My first email client. TLSEmail Testing Body");
}
Output:-
TLSEmail Start
Calling getPasswordAuthentication
After getPasswordAuthentication
Message is ready
com.sun.mail.smtp.SMTPSendFailedException: 554 Email rejected
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2358)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1823)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1300)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at EmailUtil.sendEmail(EmailUtil.java:48)
at MyEmail.main(MyEmail.java:38)
What is the problem here.
Here is class EmailUtil:
public class EmailUtil {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply#example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply#example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This client sends email using gmail SMTP server.
If you read here https://serversmtp.com/port-outgoing-mail-server/ and also here https://getmailspring.com/setup/access-yahoo-com-via-imap-smtp
You will notice that yahoo uses port 465 and in your code i see 587
I'm trying to send a email with a Table in string with RTF, but when I check the email the message body, the table lost the format, so I wondering what I'm doing wrong, this is the following chunk of code to send and email
public static void send(String asunto, String texto, String emailDestinatario){
final String username = "myemail#gmail.com";
final String password = "mypass";
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");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse( emailDestinatario));
message.setSubject(asunto);
message.setText(texto);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
what others configurations I need to send and email and recogniz me the format of table?
This is a document example to send via email
I get something like that(the table lost the format)
TARIFAS EMPLEADOS
TARIFA
IVA
TOTAL
EMPLEADOS HASTA $150.000.000
94,000
15,040
109,040
EMPLEADOS MAYOR DE $150.000.000
160,000
25,600
185,600
Have you tried something like :
MimeMessage message = new MimeMessage(sesion);
.
.
.
//Config your message....
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("RTF HTML TEXT", "text/html");
mp.addBodyPart(htmlPart);
message.setContent(mp);
Transport.send(message);
I need to send mail from my gmail account to another. I used the following code.
String fromaddress = "xxx#gmail.com";
String password = "yyy";
String hostname = "smtp.gmail.com";
String hoststring = "mail.smtp.host";
String toaddress = "yyy#gmail.com";
String emailcontent;
Properties properties = System.getProperties();
properties.setProperty(hoststring, hostname);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromaddress));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
message.setSubject("hi");
emailcontent = "hi...";
message.setText(emailcontent);
System.out.println(emailcontent);
Transport.send(message);
System.out.println("Sent....");
}catch (MessagingException mex)
{
mex.printStackTrace();
}
But i get the error as follows...
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25
How am i to solve this. Can you please help me out.
public static void sendEmail(Email mail) {
String host = "smtp.gmail.com";
String from = "YOUR_GMAIL_ID";
String pass = "YOUR_GMAIL_PASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set sender
message.setFrom(new InternetAddress("Senders_EMail_Id"));
// Set recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));
// Set Subject: header field
message.setSubject("SUBJECT");
// set content and define type
message.setContent("CONTENT", "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mex) {
System.out.println(mex.getLocalizedMessage());
}
}
}`
I think this should do the trick.
I think you need to change the port no. 25 to 587
you can get help from
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
gmail setting help link:
http://gmailsmtpsettings.com/
Just adding few more tweaks to the question above:
Change the port to 465 to enable ssl sending.
I don't think above code will work, as you need to have an authenticator object too. As smtp also requires authentication in case of gmail.
You can do something like:
Have a boolean flag,
boolean authEnable = true; //True for gmail
boolean useSSL = true; //For gmail
//Getters and setters for the same
if (isUseSSL()) {
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
}
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com", "xyz"));
}
};
if (isAuthEnable()) {
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}
recently i've been working on an automatic daily mail sender plus a weekly mail inside two different threads on my project.
The mail server is a MS Exchange (don't remember the version)
When the only daily mail was running, my mails were sent just fine.
Now that i've added another thread for the Weekly mails i have some of these issues:
Only one of the threads are able to send the email ( never both )
None of the threads are able to send email
On my logs i don't have evidence of errors, it seems the connection to the smtp server is not the problem and that the mail has been sent, but when i check my mailbox, no mails at all are arrived.
I'll post you the code about my Email class
public class Email {
boolean debug = false ;
String smtpServer = null;
int smtpPort = null;
String smtpSender = null;
String smtpUser = null;
String smtpPassword = null;
public Email(){
smtpServer = Config.SMTP_SERVER;
smtpPort = Config.SMTP_PORT;
smtpSender = Config.SMTP_SENDER;
smtpUser = Config.SMTP_USER;
smtpPassword = Config.SMTP_PASSWORD;
}
public void postMailAttach( String recipients[], String subject, String message, String filename ) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, null);
//SET SERVER FOR MESSAGE
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(smtpSender));
InternetAddress[] toAddress = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++){
toAddress[i] = new InternetAddress(recipients[i]);
}
//SET RECIPIENTS FOR MESSAGE
msg.setRecipients(Message.RecipientType.TO, toAddress);
//SET SUBJECT
msg.setSubject(subject);
//SET BODY PART OF MESSAGE
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
//GET FILES TO ATTACH
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
//SET FILE NAME
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
//SEND THE EMAIL
Transport transport = session.getTransport("smtp");
transport.connect(smtpServer,smtpPort,smtpUser,smtpPassword);
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
}
public void postMail (String recipients[], String subject, String message) throws MessagingException{
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
//session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(smtpSender);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
//msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport transport = session.getTransport("smtp");
transport.connect(smtpServer,smtpPort,smtpUser,smtpPassword);
transport.sendMessage(msg,msg.getAllRecipients());
transport.close();
}
Thank you in advice for any suggestion.
After initializating properties like username, password etc
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");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
hope this would help
I am trying to send mail to my friends through my Java Mail application. I am able to do it successfully however the receiver's column in the mailbox shows the complete email address rather than the name of the sender. I tried changing various parameters but still the mailbox would show the full e-mail address rather than the name of the sender.
using this method to send the message:
public void send(String key){
String to=key;
String from="mygmailid";
String subject="wassp";
String text="Hello";
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.user", "myname");
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 mailSession=Session.getDefaultInstance(props);
Message simpleMessage=new MimeMessage(mailSession);
InternetAddress fromAddress=null;
InternetAddress toAddress=null;
try{
fromAddress=new InternetAddress(from);
toAddress=new InternetAddress(to);
}
catch(AddressException e){
e.printStackTrace();
}
try{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
catch(MessagingException e){
e.printStackTrace();
}
}
I am calling this method as:
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("friendmail#gmail.com");
}
You can set a name in the InternetAddress using
new InternetAddress("mail#example.com", "Your Name");
You should use the two string constructor of InternetAddress to pass in both the e-mail address and the person's name. The resulting e-mail will contain a string like Jarrod indicated.
InternetAddress fromAddress=new InternetAddress("my#example.com", "John Doe");
try {
String from = " EMAIL ID";
String SMTP_AUTH_PWD = " PASSWORD ";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.auth", "true");
String SMTP_HOST_NAME = "smtp.gmail.com";
int SMTP_HOST_PORT = 465;
javax.mail.Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = ((javax.mail.Session) mailSession)
.getTransport();
javax.mail.Message message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("", "text/plain");
message.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(receiver));
transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, from,
SMTP_AUTH_PWD);
message.setFrom(new InternetAddress(from," YOUR PREFERED NAME "));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
message.setContent(multipart);
transport.sendMessage(message,
message.getRecipients(javax.mail.Message.RecipientType.TO));
}
How the from field is displayed is a client specific implementation detail.
Usually if the sender is in the form of "Sender Name" <sender#domain.com> the client will do the correct thing depending on configuration.
Some clients will infer the name information from their address book information if it is missing.
The answers above are correct but I found I needed to place in a try catch for it to work, here's what I found worked from sendemailwebapp demo application.
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(userName, "YourName"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
Try this code within the try block.You can initialize your name within the setFrom() method of MimeMessage.
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
ie,
try{
simpleMessage.setFrom(new InternetAddress("Your mail id", "Your name"));
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
transport.connect("smtp.gmail.com",465, "myid#gmail.com", "mygmailpassword");
transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
transport.close();
}
You can force to specify the sender's name by using the greater than and less than Symbol < > as per the following format:
String from="John Smith<friendmail#gmail.com>";
.
.
.
fromAddress=new InternetAddress(from);
or
public static void main(String[] args) {
MailSender mailer=new MailSender();
mailer.send("John Smith<friendmail#gmail.com>");
}
When receiving the email, the email recipient will see the name "John Smith" in his inbox. (Most email programs shows the name if specified. e.g. Outlook, gmail, hotmail, etc...)