I'm trying to do an Android app that sends an image automatically without any intervention from the user.
I'm using javax.mail jar (and the activation.jar and additional.jar) in order to do so.
I'm doing the following
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.ssl.enable",true);
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER,PASS);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("*******#gmail.com"));
message.setSubject("Email Subject");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("******#gmail.com"));
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<img src=\"image.gif\"/>","text/html");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(new File(ruta));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("picture.gif");
messageBodyPart.setDisposition("inline");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
When I execute this code, I get the following error
W/System.err(24907): javax.mail.MessagingException: IOException while sending message;
W/System.err(24907): nested exception is:
W/System.err(24907): javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
W/System.err(24907): boundary="----=_Part_0_1095625208.1397499270313"
W/System.err(24907): at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1182)
W/System.err(24907): at javax.mail.Transport.send0(Transport.java:254)
W/System.err(24907): at javax.mail.Transport.send(Transport.java:124)
Any idea on how can I solve this?
I'm using a Debian 64-bits computer and Eclipse Java EE IDE for Web Developers - Kepler. if it's needed for the solution...
DCH is Data Content Handler. MimeType handlers seem to be not configured correctly.
If you can download and use latest 1.5.* version of java mail api, this error should be getting resolved.
Otherwise, within the code you can execute some statements to set the MimeType handlers.
Add following code snippet to your mail module and is available for the mail Session.
MailcapCommandMap mailcapCommandMap = new MailcapCommandMap();
mailcapCommandMap.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed; x-java-fallback-entry=true");
CommandMap.setDefaultCommandMap(mailcapCommandMap);
You can extend this for additional MimeTypes
mailcapCommandMap.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mailcapCommandMap.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mailcapCommandMap.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mailcapCommandMap.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
Refer To:
javax.activation.MailcapCommandMap.addMailcap(java.lang.String)
Add entries to the registry. Programmatically added entries are
searched before other entries.
Apart from this method, read entire documentation on this class.
I had this same problem for my release mode android app, it works as expected for the debug mode.
Adding the following lines in the proguard file will fix the problem:
-keep class com.sun.mail.handlers.**
-dontwarn com.sun.mail.handlers.handler_base
Related
I was using the JavaMail API to send an email containing a text file. This code I wrote was working perfectly fine last week, however I logged on today and ran the program and received the error in the image I've attached at the bottom. I updated to the newest version of java 8 and still receive this error. (I have to use java 8 for the project for work) I looked at the java 8 patch notes for this update and saw the removed of root CA Certificates and I'm not sure what to think/do. I am posting this question because I cannot find any solution in the other tons of questions about this.
I am running Java 8 (jre 1.8.0_221) and previously was running jre 1.8.0_211. I do not know what changed as it stopped working today with v.211 and is also not working after I updated to the most recent version of Java 8 with v.221. I have tried various other properties with no success. I'm not sure if it is the Java removal of something specific (which I doubt) or if it has to do with firewall permissions any smtp permissions I may or may not have. Anyways, the code is below for the email sending portion and the code fails at Transport.send(message); with error "Could not convert socket to TLS"
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUsername, u2);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(prop.getProperty("Message"));
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(prop.getProperty("Message"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(prop.getProperty("text") + ".txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(prop.getProperty("filename"));
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent successfully.\n");
Error Message I am receiving. Hopefully I have explained thoroughly enough. This is only my second question I've asked on here. Any help is appreciated, thanks.
I am not an expert, but...
You may be impacted by intentional distrusting of some root certificates in April 2019, or whenever they were applied in your environment (re: https://blogs.oracle.com/java-platform-group/jdk-distrusting-symantec-tls-certificates).
We are moving some old code to java11.We are creating a smtp client. The coe compilation fails when we use java11.
error: package sun.net.smtp is not visible
[javac] sun.net.smtp.SmtpClient SMTP = new sun.net.smtp.SmtpClient(SMTP_SERVER);
[javac] ^
[javac] (package sun.net.smtp is declared in module java.base, which
does not export it)
looks like smtp package support is removed from the java11. Any suggestions will be helpful.
Regards,
Akj
You can use JavaMail API to send email to get this sorted. Go to below link and download the .jar file and add to your project. If not you can add it as a maven dependency.
https://mvnrepository.com/artifact/javax.mail/mail/1.4.7
A sample code to talk to SMTP server and send email as per below.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc#abcmail.com"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("to#abcmail.com"));
message.setSubject("Mail Subject");
String msg = "This is a sample email ";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
Your configurations can be done with a Java Properties object
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.abcmail.com");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.abcmail.com");
You should use JavaMail, a Java API for sending and receiving emails via SMTP, POP3, and IMAP.
First, have a look at Oracle docs about sending mail in Java here
The sample code below is extracted from the Oracle docs and illustrate how you should send email using the JavaMail API.
Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("me#example.com");
msg.setRecipients(Message.RecipientType.TO,
"you#example.com");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport.send(msg, "me#example.com", "my-password");
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
Also, note that to send a mail with Java Mail you need a valid SMTP server and an account in that server.
I'm trying to figure it out of how to open an email using javax.mail. My goal is to provide a feature where a user clicks on a button and a default email will open with an attachment. So far, I'm using javax.mail and what it does is just sending the email right when the button is click. Is there a way to just open the email without direct sending? If so, how? I'm using Java 8.
I can't use the 'mailto:' because I need to attach a png file when a user opens an email. Also I'm not sure if I should use ProcessBuilder to open outlook because every user's machine will have a different userName within the C Drive or I'm not sure how to use that.
Here's my code just in case if you need it
String result;
String to = "....gov";
String from = "....gov";
String host = "....gov";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(emailFrom));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo));
message.setSubject("meh!");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("text body mehmehmehmeh");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "testing.png";
DataSource source = new FileDataSource(filename);
String imageString = toDataURL.substring("data:image/png;base64," .length());
byte[] contentdata = imageString.getBytes();
ByteArrayDataSource ds = new ByteArrayDataSource(contentdata, "image/png");
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart); //
// Send the complete message parts
message.setContent(multipart);
Transport.send(message);
result = "Sent message successfully....";
}catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
Is there a way to just open the email without direct sending? If so, how?
Don't call Transport.send. Then follow the steps in this answer. and start with msg.saveChanges(). There is an X-Unsent header in that answer that can be used to toggle some outlook features.
Also I'm not sure if I should use ProcessBuilder to open outlook because every user's machine will have a different userName within the C Drive or I'm not sure how to use that.
You use File.createTempFile​ as this will account for user names. If you need to save in a different location you can read from System.getProperty​ or if you are only targeting Windows machines you can read from System.getenv. To list all the environment vars you can type set in the command window.
Here is the exception I get sometimes when trying to send mail with attachments on Appengine :
java.lang.NoClassDefFoundError: java.awt.Component is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.apphosting.runtime.security.shared.stub.java.awt.Component.<clinit>(Component.java)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:375)
at javax.activation.MailcapCommandMap.getDataContentHandler(MailcapCommandMap.java:588)
at javax.activation.MailcapCommandMap.createDataContentHandler(MailcapCommandMap.java:542)
at javax.activation.DataHandler.getDataContentHandler(DataHandler.java:617)
at javax.activation.DataHandler.getInputStream(DataHandler.java:240)
at javax.activation.DataHandlerDataSource.getInputStream(DataHandler.java:708)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:764)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:718)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:548)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:133)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:1393)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1366)
at javax.mail.Transport.send(Transport.java:76)
at javax.mail.Transport.send(Transport.java:48)
I use this code to send a mail :
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(mailSession);
MimeMultipart multipart = new MimeMultipart();
// first part (the html)
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlText, "text/html");
multipart.addBodyPart(htmlPart);
// second part (the image)
BodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setFileName("screenshot.jpg");
DataSource imageSrc = new ByteArrayDataSource(image, "image/jpeg");
attachmentPart.setDataHandler(new DataHandler(imageSrc));
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
message.saveChanges();
Transport.send(message);
When this exception occurs on an instance, it becomes unstable and is no longer able to send emails with attachment. The only solution I found is to kill the instance and start a new one.
Is "image" really a byte array?
The stack trace suggests that you've set the attachment as an Image object, so JAF is trying to find a DataContentHandler to convert it to a byte array, and that DataContentHandler is using an AWT class that's not allowed. There's no such DataCOntentHandler configured by default so I don't know where it's coming from. Maybe GAE has a different configuration?
Also, what version of JavaMail are you using?
i have using the following code for sending mail within a domain.
public void sendMail(String mailServer, String from, String to,
String subject, String messageBody, String[] attachments)
throws MessagingException, AddressException {
// Setup mail server
Properties props = System.getProperties();
props.put("mail.smtp.host", mailServer);
// Get a mail session
Session session = Session.getDefaultInstance(props, null);
// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);
// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();
// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);
// add any file attachments to the message
addAtachments(attachments, multipart);
// Put all message parts in the message
message.setContent(multipart);
// Send the message
Transport.send(message);
System.err.println("Message Send");
}
protected void addAtachments(String[] attachments, Multipart multipart)
throws MessagingException, AddressException {
for (int i = 0; i < attachments.length ; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// assume that the filename you want to send is the same as the
// actual file name - could alter this to remove the file path
attachmentBodyPart.setFileName(filename);
// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}
but if with the same code i try to send an email outside the domain, say i am sending email from mjsharma#domain.com to mhsharma#gmail,com then it fails and gives me the following error. 550 5.7.1 Rcpt command failed: Mail denied due to site's policy
Am i missing something in the above code.
Please help me
I suspect that's not a problem in your code, but in your mail server (sendmail?) configuration. I would talk to whoever administers your mail infrastructure.
It's likely that your local mail server requires you to authenticate before sending mail out into the world. This is a common policy to prevent spammers from relaying their mail through it.
Assuming your machine has Outlook installed... have you tried using moyosoft's java outlook connector? it's pretty simple to use and passes through network restrictions because it connects to your Outlook application and then sends the mail, so any restriction on smtp ports or servers/proxy policies will be ignored if your Outlook client is working fine.
if you are doing it with command line server-side then i guess this answer is useless for you.
Source: i had similar problem (not same error code, more like an intranet restriction) and using this library solved my problem because of the posted above.