SMTP measurement and evaluation - java

I'm trying to learn about how SMTP works (JAVAMAIL API).
I wrote a code that send message to a given list of adresses.
I used as properties for the SMTP server:
mail.smtp.auth= true
mail.smtp.starttls.enable= true
mail.smtp.host= smtp.gmail.com
mail.smtp.port= 587
the send email code is:
public void sendEmail(String emailRecip, String subject, String texte) {
boolean isMsgSent = false;
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
String address = emailRecip;
InternetAddress[] iAdressArray = InternetAddress.parse(address);
message.setRecipients(Message.RecipientType.TO,iAdressArray);
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(texte);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
message.setContent(mp);
Transport.send(message);
isMsgSent = true;
} catch (MessagingException e) {
//...
}
}
This code works well, but i would like to know how can i:
1- calculate the avrage time of message delivery
2- calculate the impact of the size of the message
3- evaluate the impact of sending multiple messages on the same SMTP
I found many documentations that talke about those issus but i don't know how to put it in a code example, is there any other properties i must to add it to SMTP server?

JavaMail isn't going to do this for you. You're going to need some performance analysis tools. Find one you like and then apply it to this task. Or just do something simple yourself using System.currentTimeMillis() to measure the amount of time an operation takes.
See also this JavaMail FAQ entry for sending multiple messages with a single connection.

Related

AWS lambda unable to send smtp email

I have a simple AWS lambda request handler running that sends an email using smtp. When I put this code into a local main() function, it runs well and sends the email. When running on aws, I keep getting the following javax.mail.MessagingException: 501 Syntax: HELO <hostname> error. Is there something that needs to be changed in AWS for the mail to go through? Here is my code:
Properties mailProps = new Properties();
mailProps.setProperty("mail.smtp.host", sesHost);
mailProps.setProperty("mail.smtp.port", port);
mailProps.setProperty("mail.smtp.user", user);
mailProps.setProperty("mail.smtp.auth", "true");
PasswordAuthentication auth = new PasswordAuthentication(user, password);
mailSession = Session.getInstance(mailProps, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return auth;
}
});
String toAddress = "example#example.com";
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress("noreply#example.com", "Example"));
message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
message.setSubject("test subject");
message.setContent("content content","text/html; charset=utf-8");
System.out.println("Sending email to" + toAddress);
Transport.send(message);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Failed to send email");
}
There is a need to attach a Security Group with your Lambda which has port 25 open in its outbound rules.
In the Lambda configurations -
Select VPC (create one if there is no existing VPC in account)
Select subnets (create more than one in multiple AZs)
Select the Security group (which has port 25 open in Outbound rules or All traffic permission)
This should work.

java- How to use services for sending email?

I have a simple web application where different users can log into it. One of the important feature is user can access a document and send email of it's content to an outsider like third party. Below is just how the email looks like to give an idea:
It's pretty self explanatory and I can send to multiple user if I want like abc#example.com,efg#hotmail.com,... in the field box shown.With all this, I am using Java Mail API to make it work and after hitting the send button,it sends directly to the recipient.No issue at all.
Now, I want to modify this by doing this email feature as a service.What this means is when I send the email,the content and info filled in will be stored in a table in MYSQL and the service(running in background) will pick up from the table and do the sending.
This is my function:
public void sendEmail(String recipient, String subject, String content,
String host, String port, final String senderaddress,
final String password) {
try {
System.out.println("Please Wait, sending email...");
/*Setup mail server */
Properties props = new Properties();
props.put("mail.smtp.host", host); //SMTP Host
props.put("mail.smtp.port", port); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderaddress, password);
}
};
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(senderaddress));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(content);
try {
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Can this be done in the way I want because I am unsure how to make it work?
1 ) After hitting Sending mail button from UI, You need to call a method for saving data like recipient, subject, content in DB
2)Write an email sender Service which retrieves non_delivered / pending mail from DB table and send it through Java Mail API
3)Scheduled email sender service with the help of ScheduledExecutorService

Javamail rate for the client exceeded

I need to send at least 200 messages from a stretch. When the program starts, send mail successfully to 15 or 17, then I get this error:
MESSAGE ERROR:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
What I can do?
CODE JAVA
public void mandarEmail(String correos, String mensaje, String asunto) {
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("docemail#usmp.pe", "docpass");
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("USMP - FN <documentos-fn#usmp.pe>"));
message.setSubject(asunto);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(correos));
message.addRecipients(Message.RecipientType.BCC, new InternetAddress[]{new InternetAddress("ivan_pro_nice#hotmail.com")});
message.setContent(mensaje, "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect("docemail#usmp.pe", "docpass");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
That's the server you're connecting to, and not a client issue. Here's a doc on how to parse SMTP codes from the server.
A mail server will reply to every request a client (such as your email
program) makes with a return code. This code consists of three
numbers.
In your case, you're getting 421.
You probably need to pay for a "business" account from your mail server vendor so they'll let you send more email.
if you want to send single email to 200 clients. Than u can add an array of reciever's email addresses of size upto 50.
but i you want to send different msg for each email. Then you can create a new connection to email server with a counter that counts send emails as well as it counts 15 it should create a new connection.
to test your code use mailtrap.io

Delivery Confirmation For Sent Mail

My requirement is to send E-Mail Alerts to various customers for our client for which, we're planning to use JavaMail API. However, once mail is sent, we need to update status in DB as Sent/Delivered/Failure depending on the status of the mail. Please tell me how do we get Delivery Notification for the mail reaching the Mail Server of the Receiver. It's not necessary to ensure whether the person has read the mail or not, however, it will be great if we'll be able to know that. The mandatory thing to check is for delivery. How can we get the status. What I read was that using 'SMTPMessage' we can get the status, however, I couldn't find a code sample for how to read the Notification. I am putting my code which is very sample of what I have done till now. Please let me know how I can achieve the thing which we are trying to fulfill.
public class MailSender {
private int port = 25;
private String host = "testmailsrvr";
private String from = "test#test.com";
private boolean auth = true;
private String username = "test";
private String password = "test#123";
private Protocol protocol = Protocol.SMTP;
private boolean debug = true;
public void sendEmail(String strMailID, String strSubject, String strBody) throws MessagingException{
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
case SMTP:
props.put("mail.smtp.ssl.enable", false);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = {new InternetAddress(strMailID)};
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject(strSubject);
message.setSentDate(new Date());
message.setText(strBody);
Transport.send(message);
}
}
You'll want to read these JavaMail FAQ entries:
If I send a message to a bad address, why don't I get a SendFailedException or TransportEvent indicating that the address is bad?
When a message can't be delivered, a failure message is returned. How can I detect these "bounced" messages?
Then read the javadocs for the com.sun.mail.smtp and com.sun.mail.dsn packages to learn about Delivery Status Notifications.
You will have to approach the issue differently. The Transport.send() method will throw a SendFailedException if it runs into problems sending to any of the recipients. The exception will give you information on which recipient addresses failed. You should catch that exception, get the failing addresses and record them.
You might want to look into http://www.ultrasmtp.com. This service will send a notice back to the recipient upon the message being accepted, deferred, or refused by the receiving mail server. There is also an option to setup alerts for opened messages.

How to send sms alerts to mobile using java?

Im developing a simple Email Application, I have done sending email using java with following code.`
public class SendMail {
public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "mnmnn";
String from = "xyz#gmail.com";
String toAddress = "abc#gmail.com";
String filename = "C:/Users/hp/Desktop/Write.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport tr = session.getTransport("smtps");
tr.connect(host, from, Password);
tr.sendMessage(message, message.getAllRecipients());
System.out.println("Mail Sent Successfully");
tr.close();
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}
}`
I want to develope SMSAlert application using java. I want to get sms alerts to my number whenever i get mail. Is it possible in java. Thanks in advance.
An easy and free way to accomplish this is to send an email to your sms inbox.
Each provider has a different domain, but say for sprint emails sent to [mynumber]#messaging.sprintpcs.com will be texted to me.
There doesn't seem to be much of a delay, we have monitoring processes that send out emails and texts this way on error conditions and they arrive simultaneously.
Of course if your recipients are spread across multiple networks maintaining this sort of system gets trickier, because you've got to look up the email domains.
There have been quite a lot of posts about this already.
My advice is to go through a third party provider such as aspsms.com and then to use their API (web service or wathever).
This one has a .Net API, but with Java, you should be able to use the SOAP webservice.
See this answer
This discussion thread about Kannel and SMS Gateways might be of some help.

Categories