So I have the problem with the Javamail where if I send an attachment in the mail the body disappears. When I don't send an attachment with the mail i can just see the body.
My GMailSender.java:
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
_multipart = new MimeMultipart();
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception
{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setText(body);
message.setDataHandler(handler);
if(_multipart.getCount() > 0)
message.setContent(_multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}
public void addAttachment(String filename) throws Exception
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
My MainActivity.java
Button bt_send = findViewById(R.id.Alert);
bt_send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
BackgroundMail bm = new BackgroundMail(context);
bm.setGmailUserName("***#gmail.com");
bm.setGmailPassword("******");
bm.setMailTo(to);
bm.setFormSubject(value + " DOC/" + mTvResult.getText().toString());
bm.setFormBody("Document Nummer:\n" + mTvResult.getText().toString() + "\n \nDocument Type:\n" + value);
if (images.size() > 0) {
for (Object file : images) {
bm.setAttachment(file.toString());
}
}
bm.setSendingMessage("Loading...");
bm.setSendingMessageSuccess("The mail has been sent successfully.");
bm.send();
}
});
So how can i add an attachment while still being able to see the body itself?
Thanks in advance!
It looks like you copied GMailSender from someone else. You should start by fixing all these common mistakes.
You never call the addAttachment method. (Note that you could replace that method with the MimeBodyPart.attachFile method). Please remember to post the code that you're actually using.
The key insight that you're missing is that for a multipart message the main body part needs to be the first body part in the multipart. Your call to Message.setContent(_multipart); overwrites the message content that was set by your call to message.setDataHandler(handler);, which also overwrote the content set by your call to message.setText(body);.
Instead of setting that content on the message, you need to create another MimeBodyPart, set the content on that MimeBodyPart, and then add that MimeBodyPart as the first part of the multipart.
Related
I am developing an app where I need to set image in a header and footer of a mail. I saw method setHeader(String header-name, String header_value) but when I put into it a path to my image I don't get anything.
This is my code:
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg");
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
As you can see in part
msg.setHeader("image1", "D:\\broki\\src\\main\\resources\\imageHeader.jpg")
I put some key and value which is path to my Image which I want to set into header. But nothing happens. Can someone help me?
The word "header" in a MIME message refers to a section of the message that has "key: value" fields. This section is called "header" because it's transmitted before the "body" content of the message. The headers are for things like "Date", "Subject", "Content-Type".
The word "header" does not refer to a graphical header that would be visible on the screen or when printed. To add this type of a header, you have to modify the content of the message. In your program, that's stored in the htmlBody variable.
I don't think you can simply modify htmlBody to add a header to it, without knowing how it is structured. In the general case, the page header has to be incorporated in the HTML message design from the start.
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 got following error when trying to send email via Java Mail API? What does this error mean?
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2210)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Here is my code, i set all parameters (from, to , subjects and attachments)
public static void send(MailUtil mailUtil) throws MessagingException {
MimeMessage message = new MimeMessage(session);
if (props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER) != null) {
message.setFrom(new InternetAddress(props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER)));
} else {
message.setFrom(new InternetAddress(mailUtil.getFrom()));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailUtil.getTo()));
if (mailUtil.getBcc() != null && mailUtil.getBcc().trim().length() > 0) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailUtil.getBcc()));
} else {
message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(""));
}
message.setSubject(mailUtil.getSubject(), "UTF-8");
// Check for files list and attach them.
if (mailUtil.attachmentFiles != null && mailUtil.attachmentFiles.size() > 0) {
Multipart multipart = new MimeMultipart();
// Set content.
BodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(mailUtil.getContent(), "text/plain; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// Attach files.
for (File file : mailUtil.attachmentFiles) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
//message.setContent("<h1>Hello world</h1>", "text/html");
message.setContent(mailUtil.getContent(), "text/html; charset=UTF-8");
}
Transport.send(message);
}
I just think is there any problem with my paramters?
Belows is my configuration
mail.smtp.port=465
mail.smtp.starttls.enable=true
mail.smtp.auth=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.timeout=25000
mail.smtp.host=smtp.gmail.com
mail.username = username#gmail.com
mail.password = mypassword
mail.sender = sender#gmail.com
mail.receiver = receiver#gmail.com
mail.subject = mysubject
I am using google mail server! I dont' think there is problem there!
Belows is session initiation
final String userName = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_USERNAME);
final String passWord = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_PASSWORD);
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,
passWord);
}
});
I believe it absolutely relates to server configuration.
When I change the port configuration from 465 to 587, it solves my problem!
Anyway, thank you guy for your help!
Your code and configuration contain many of these common mistakes. In particular, the use of Session.getDefaultInstance may mean you're not using the configuration you think you're using. If fixing that doesn't solve your problem, post the JavaMail session debug output.
I'm not sure why you use a "mail" object to setup the connection properties, instead try this, it should work, I've tested myself:
private Properties props;
props = System.getProperties();
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.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS HERE"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECEIVER EMAIL ADDRESS HERE"));
message.setSubject("SUBJECT");
message.setText("THE EMAIL TEXT");
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
}
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);
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