Java mail sender's address displayed rather than his name - java

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...)

Related

How to send simple Email using Javamail?

i am creating a simple java mail program,the program is working ok and the last system print also working .but the problem is i dint received the mail in outlook.here i am using the company outlook.please some one help me.
i am attaching my code here
enter code here
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail
{
public static void main(String[] args)
{
String host = "compny host";
String from = "mail id";
String to = "usr#some.com";
String subject = "birthday mail";
String messageText = "I am sending a message using the"
+ " simple.\n" + "happy birthday.";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("compny host", host);
props.put("mail.smtp.port", "25");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try
{
Message msg = new MimeMessage(session);
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);
Transport.send(msg);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
output
Sent message successfully....
"Compny host" doesn't seem like correct host. Check out this tutorial http://www.tutorialspoint.com/java/java_sending_email.htm and here you have also a few examples of sending emails in Java Send email using java
I do expect that you are using the correct host on your side.
But you are missing Username and Password.
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
transport.sendMessage(message, message.getAllRecipients());
or you can use the Authenticator:
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

Gmail api client library cannot send email java

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

Send a table inside of RTF message JavaMail

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);

AuthenticationFailedException while sending email using Java

I'm trying to send email using java API and i'm giving the right emailid and password but still i get AuthenticationFailedException.
I also tried giving host=mail.smtp.port and changing port to 587 still i end up getting the same error..
Please help me where i'm going wrong..?
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "to#gmail.com";
// Sender's email ID needs to be mentioned
final String from = "from#gmail.com";
// Assuming you are sending email from localhost
final String host = "smtp.googlemail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.user", from);
//properties.setProperty("mail.smtp.password", "xyz");
properties.setProperty("mail.debug", "false");
properties.setProperty("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.port", "587");
// Get the default Session object.
// Session session = Session.getDefaultInstance(properties);
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "xyz");
}
});
session.setDebug(true);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
// Transport.send(message);
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Error:
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
Just check if you have enabled logging in from "Less Secure Apps" using this link. This setting needs to be enabled for the account from#gmail.com.

Setting the "from" header field in Java MimeMessage not working correctly

For a web application I'm working on I made a method to send email notifications. The message has to come from a specific account, but I would like the "from" header field to read as an entirely different email address. Here is my code (I've changed the actual email addresses to fake ones):
public static boolean sendEmail(List<String> recipients, String subject, String content){
String header = "This is an automated message:<br />"+"<br />";
String footer = "<br /><br />unsubscribe link here";
content = header + content + footer;
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() {
//This is where the email account name and password are set and can be changed
return new PasswordAuthentication("ACTUAL.ADRESS#gmail.com", "PASSWORD");
}
});
try{
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("FAKE.ADDRESS#gmail.com", "FAKE NAME"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
message.setReplyTo(new Address[]{new InternetAddress("no-reply#gmail.com")});
for(String recipient: recipients){
message.addRecipient(Message.RecipientType.BCC,new InternetAddress(recipient));
}
message.setSubject(subject);
message.setContent(content,"text/html");
Transport.send(message);
return true;
}catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
For the above method sending an email with it will have the following email header:
from: FAKE NAME <ACTUAL.ADRESS#gmail.com>
I want it to read:
from: FAKE NAME <FAKE.ADRESS#gmail.com>
What am I doing wrong? Any help is appreciated!
What you are looking to do is called "spoofing." It appears as though you are using Google's SMTP servers, if this is the case, you will not be able to do this successfully. For security purposes, Google will only allow the "from" address to be the authenticated email address.
See this related question

Categories