how to send email through outlook from java - java

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.

Related

error: package sun.net.smtp is not visible

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.

Outlook and office 365 don't recognize ICS file

I'm developping a ics sender functionnality.
But i have some trouble with office 365 and outlook.
When i sent the ics file to google mail, i don't have any problem.
My event appear in the gmail.
But when i send to outlook or office 365, my appointment didn't appear but it was in the email attachment ( ATT00001.ics).
This is the code send the mail
private void generateIcal(MimeMessage message) throws MessagingException, IOException {
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=VEVENT");
message.setFrom(new InternetAddress(from));
message.setSubject(subj,"UTF-8");
StringBuffer sb = new StringBuffer();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
messageBodyPart.setHeader("Content-ID", "calendar_message");
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(txt, "text/calendar;charset=utf-8")));//very important
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
}
And this generate the ics file
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//TELELANGUE//NONSGML v1.0//EN
BEGIN:VEVENT
DTSTART:20180714T170000Z
DTEND:20180715T035900Z
SUMMARY:Fête à la Bastille
END:VEVENT
END:VCALENDAR
Thanks for your reply
Finally, I found the solution.
Looks like, we need to set "method" and "name" parameters into the BodyPart.
MessageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(buffer.toString(), "text/calendar;method=REQUEST;name=\"meeting.ics\"")));
1) Parse the ics. file and make it an event in Inbox so that you can read the event information without opening the attachment.
2) Add interactivity so that you can accept/decline the invite directly from Inbox without even opening the ics file. (This is what Gmail has now).
For more information, please see the link below:
incoming calendar invites from outlook are blank
.ics files not showing up in the Outlook.com Inbox?

Javax.mail or java email - how to open email without direct sending

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.

MailConnectException : nested exception: java.net.SocketException: Permission denied: connect

I was trying to send a mail from gmail id to another using this example. Here is my file:
public class SendHTMLEmail
// Recipient's email ID needs to be mentioned.
String to = "harsh.hr99#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", "Admin");
properties.setProperty("mail.password", "admin");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
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!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
I am running Tomcat server on localhost:9091 port. I am receiving following error:
screen shot from cmd
how do I solve this?
Well, you set "host = localhost" so your program will try to use a smtp server located at localhost. Problem is: You don't have (and don't want) a smtp server at localhost installed. At least it seems like that.
I think what you want to do is: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you trying this example you will need to keep in mind not to publish it because it contains hard-coded gmail credentials.

Java add header in MimeMessage msg

Problem that i'm solving is that when i send mail if the recipient (to mails, cc/bcc) not exist, i don't want sender to get Delivery Status Notification (Failure) mail.
The solution that i'm implementing is adding new header in mail Prevent-NonDelivery-Report
I want to add new header in MimeMessage msg in java
// this is part of the code that defined the mime message
Session session = Session.getDefaultInstance(props, null);
// we create message
Message msg = new MimeMessage(session);
// this code is not working for me
msg.addHeader("Prevent-NonDelivery-Report", "");
I found the solution i add props.setProperty("mail.smtp.dsn.notify", "NEVER") to the property of the session and that fix my problem
On behalf of the OP:
I found the solution. I add:
props.setProperty("mail.smtp.dsn.notify", "NEVER")
to the property of the session and that fix my problem.

Categories

Resources