So I have sent an email in Java, however It doesn't format the email as I'd like. Instead of a formatted email like this:
Hello John,
Welcome to X.
Thanks,
Johnathan.
It would show:
Hello John, Welcome to X. Thanks, Johnathan.
This is the code:
public class MailReceipt {
String receipt;
String email;
public MailReceipt(String message, String email) {
this.receipt = message;
this.email = email;
}
public void sendMessage() {
final String username = "abc123#gmail.com";
final String password = "abc123";
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(email));
message.setSubject("DO NOT REPLY: A receipt regarding your recent purchase.");
message.setContent(receipt, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("The mail was sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I am using '\n' tags in the string, however it doesn't seem to work here. Would I need to make use of html in Java? If so, could I get some examples?
You've said its content-type is HTML, so use HTML. A newline isn't significant in HTML. Try <p>, or <br/>.
Related
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);
}
});
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
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);
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
Is it possible to use Java to send an email such that I can see multiple recipients in the to/cc/bcc fields?
In other words, something like this:
From: foo#bar.com
To: user1#lol.com; user2#lol.com; user3#lol.com; user4#lol.com
Cc: admin1#lol.com; admin2#lol.com
I searched on Google but found no conclusive results, so any advice would be much appreciated.
Yes it is!
check out the javax.mail library.
Here is a code example:
class EmailSender{
private Properties properties;
private Session session;
private Message msg;
private final String SENDER_EMAIL = "your.email#whatever.com";
private final String PWD = "***********";
public void sendMail(String body) throws Throwable{
initMail();
msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("SENDER_EMAIL"));
//HERE YOU CAN CHOOSE BETWEEN TO, CC & BCC
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email2"));
msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email"));
msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email2"));
msg.setSubject("SUBJECT");
msg.setText(body);
//TRANSPORT
Transport.send(msg);
System.out.println("message sent!");
}
private void initMail(){
//PROPERTIES
//I choosed GMAIL for the demonstration, but you cant choose whatever you want.
properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
//AUTHENTICATION
session = Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER_EMAIL, PWD);
}
});
}
}
Don't forget to import the javax.activation library.
Yes it is.
How to do it - depends on the library you're using.