Sending e-mail via lua nginx timeout error - email

I'm trying to send e-mail via lua+nginx.
Lapis (Lua) code
local smtp = require("socket.smtp")
app:get("/ee", function(self)
local from = "<mail0#mydns.name>"
local rcpt = {
"<mail1#gmail.com>"
}
local mesgt = {
headers = {
to = "PP <mail1#gmail.com>",
cc = '"V.V." <mail2#gmail.com>',
subject = "My first message"
},
body = "I hope this works. If it does, I can send you another 1000 copies."
}
local r, e = smtp.send{
from = from,
rcpt = rcpt,
source = smtp.message(mesgt),
server = "127.0.0.1",
port = 25
}
return "R:" .. tostring(r) .. " E: " .. tostring(e)
end)
gives timeout error (after several seconds passed): "R: nil E: timeout"
Nginx config is:
http{
server{
listen 9000;
location = /cgi-bin/nginxauth.cgi {
add_header Auth-Status OK;
add_header Auth-Server 127.0.0.1; # backend ip
add_header Auth-Port 25; # backend port
return 200;
}
}
}
mail {
auth_http localhost:9000/cgi-bin/nginxauth.cgi;
server {
server_name mydns.name;
listen 25;
protocol smtp;
proxy on;
timeout 5s;
proxy_pass_error_message on;
#smtp_auth login plain;
xclient on;
smtp_auth none;
}
}
I do not understand the core of mail server. How to configure? How to use nginx server? I think timeout error appears due to mail-server just redirect but doesnt process email data, am I right? Or what have I do to fix with error?

Related

Sending Email With Lua

How would you send an email using Lua?
The team I'm working with have a mail server, is that of any relevance?
Here is the code I'm using:
function send_email (email_to, email_subject, email_message)
local SMTP_SERVER = "mail.server.com"
local SMTP_AUTH_USER = "mail#domain.com"
local SMTP_AUTH_PW = "password"
local SMTP_PORT = "587"
local USER_SENDING = "mail#domain.com"
local smtp = require("socket.smtp")
local rcpt = {email_to}
local mesgt = {
headers = {
to = email_to,
from = USER_SENDING,
subject = email_subject
},
body = email_message
}
local r, e = smtp.send{
from = USER_SENDING,
rcpt = rcpt,
source = smtp.message(mesgt),
server = SMTP_SERVER,
port = SMTP_PORT,
user = SMTP_AUTH_USER,
password = SMTP_AUTH_PW
}
end
Using the LuaSocket SMTP API.
Your example looks correct, double check the SMTP settings and log the results:
local r, e = smtp.send{
from = USER_SENDING,
rcpt = rcpt,
source = smtp.message(mesgt),
server = SMTP_SERVER,
port = SMTP_PORT,
user = SMTP_AUTH_USER,
password = SMTP_AUTH_PW
}
-- Log SMTP results and potential errors
print(r, e)
Also, ensure that you're properly chaining your SMTP message using the LTN12 module API when it is multipart:
body = ltn12.source.chain(
ltn12.source.file(io.open("image.png", "rb")),
ltn12.filter.chain(
mime.encode("base64"),
mime.wrap()
)
)
Or the Mime module API for the EOL:
body = mime.eol(0, [[
Lines in a message body should always end with CRLF.
The smtp module will *NOT* perform translation. However, the
send function *DOES* perform SMTP stuffing, whereas the message
function does *NOT*.
]])
There is a much more verbose example of this in the LuaSocket SMTP API documentation.

Dovecot IMAP and SMTP suddenly not available

Hello Community and first things First:
dovecot --version
2.2.9
dovecot -n
# 2.2.9: /etc/dovecot/dovecot.conf
# OS: Linux 3.13.0-042stab125.5 x86_64 Ubuntu 14.04.5 LTS
auth_mechanisms = plain login
dict {
sqlquota = mysql:/etc/dovecot/dovecot-dict-sql.conf
}
listen = *,[::]
log_timestamp = "%Y-%m-%d %H:%M:%S "
login_log_format_elements = user=<%u> method=%m rip=%r lip=%l mpid=%e %c %k
mail_fsync = always
mail_home = /var/vmail/%d/%n
mail_location = maildir:~/
mail_nfs_index = yes
mail_nfs_storage = yes
mail_plugins = quota acl
vmanagesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave
mmap_disable = yes
namespace {
list = yes
location = maildir:%%h/:INDEXPVT=~/Shared/%%u
prefix = Shared/%%u/
separator = /
subscriptions = yes
type = shared
}
namespace inbox {
inbox = yes
location =
mailbox Archiv {
special_use = \Archive
}
mailbox Archive {
auto = subscribe
special_use = \Archive
}
mailbox Archives {
special_use = \Archive
}
mailbox "Deleted Messages" {
special_use = \Trash
}
mailbox Drafts {
auto = subscribe
special_use = \Drafts
}
mailbox Entwürfe {
special_use = \Drafts
}
mailbox "Gelöschte Objekte" {
special_use = \Trash
}
mailbox Gesendet {
special_use = \Sent
}
mailbox Junk {
auto = subscribe
special_use = \Junk
}
mailbox Papierkorb {
special_use = \Trash
}
mailbox Sent {
auto = subscribe
special_use = \Sent
}
mailbox "Sent Messages" {
special_use = \Sent
}
mailbox Trash {
auto = subscribe
special_use = \Trash
}
prefix =
separator = /
}
passdb {
args = /etc/dovecot/dovecot-mysql.conf
driver = sql
}
plugin {
acl = vfile
acl_anyone = allow
acl_shared_dict = file:/var/vmail/shared-mailboxes.db
quota = dict:User quota::proxy::sqlquota
quota_rule2 = Trash:storage=+100%%
sieve = /var/vmail/sieve/%u.sieve
sieve_after = /var/vmail/sieve/global.sieve
sieve_max_script_size = 1M
sieve_quota_max_scripts = 0
sieve_quota_max_storage = 0
}
protocols = imap sieve lmtp pop3
service auth {
unix_listener /var/spool/postfix/private/auth_dovecot {
group = postfix
mode = 0660
user = postfix
}
unix_listener auth-master {
mode = 0600
user = vmail
}
unix_listener auth-userdb {
mode = 0600
user = vmail
}
user = root
}
service dict {
unix_listener dict {
group = vmail
mode = 0660
user = vmail
}
}
service lmtp {
unix_listener /var/spool/postfix/private/dovecot-lmtp {
group = postfix
mode = 0600
user = postfix
}
user = vmail
}
service managesieve-login {
inet_listener sieve {
port = 4190
}
process_min_avail = 2
service_count = 1
vsz_limit = 128 M
}
service managesieve {
process_limit = 256
}
ssl_cert = </etc/ssl/mail/mail.crt
ssl_cipher_list = EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA384:EECDH+aRSA+SHA256:EECD H:+CAMELLIA256:+AES256:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5 :!EXP:!PSK:!DSS:!RC4:!SEED:!ECDSA:CAMELLIA256-SHA:AES256-SHA:CAMELLIA128- SHA:AES128-SHA
ssl_dh_parameters_length = 2048
ssl_key = </etc/ssl/mail/mail.key
ssl_protocols = !SSLv3 !SSLv2
userdb {
args = /etc/dovecot/dovecot-mysql.conf
driver = sql
}
protocol imap {
mail_plugins = quota imap_quota imap_acl acl
}
protocol lmtp {
auth_socket_path = /var/run/dovecot/auth-master
mail_plugins = quota sieve acl
postmaster_address = postmaster#domain1.com
}
protocol sieve {
managesieve_logout_format = bytes=%i/%o
}
remote 127.0.0.1 {
disable_plaintext_auth = no
}
Mail.err
Nov 13 23:59:06 webdev dovecot: auth: Error: PLAIN(account#domain2.com, XXX.XXX.XXX.XXX,<y869CoDETEST4dHk>): Request 29154.1 timed out after 150 secs, state=1
Mail.log
Nov 13 23:27:54 webdev dovecot: auth: Error: LOGIN(account#domain1.com,IP.IP.IP.IP,<oN4ly+TestDZ6dHk>): Request 28118.1 timed out after 150 secs, state=1
Nov 13 23:27:57 webdev dovecot: auth: Error: PLAIN( account#domain2.com,XXX.XXX.XXX.XXX,<FAxKe+JaatES7tHk>): Request 28120.1 timed out after 150 secs, state=1
Nov 13 23:28:24 webdev dovecot: imap-login: Disconnected: Inactivity during authentication (disconnected while authenticating, waited 180 secs): user=<>, method=LOGIN, rip=ClientIP, lip=ServerIP, TLS: Disconnected, TLSv1.2 with cipher DHE-RSA-AES128-GCM-SHA256 (128/128 bits)
[...]
Nov 13 23:47:15 webdev dovecot: imap-login: Aborted login (no auth attempts in 0 secs): user=<>, rip=84.119.151.17, lip=62.75.185.32
I did not change anything on my client nor serverside setup and i suddenly could not reach the Mailserver anymore. Obviously I can reach the Server using SSH or HTTP.
I hope I provided all infos you need to help me in this situation. And am grateful for every hint to solve this as I dont even have a clue what to look for.
The error messages are talking about a timeout on the authentication, and the config shows that the authentication is using a MySQL database. For this reason I would check if the MySQL process is still up, or restart the service (if it's running as a service, which is probably the case).

Sending email using luasocket smtp and ssl

I have been trying to send an email using the code described in the post:
lua send mail with gmail account
The code by Michal Kottman is repeated below:
-- Michal Kottman, 2011, public domain
local socket = require 'socket'
local smtp = require 'socket.smtp'
local ssl = require 'ssl'
local https = require 'ssl.https'
local ltn12 = require 'ltn12'
function sslCreate()
local sock = socket.tcp()
return setmetatable({
connect = function(_, host, port)
local r, e = sock:connect(host, port)
if not r then return r, e end
sock = ssl.wrap(sock, {mode='client', protocol='tlsv1'})
return sock:dohandshake()
end
}, {
__index = function(t,n)
return function(_, ...)
return sock[n](sock, ...)
end
end
})
end
function sendMessage(subject, body)
local msg = {
headers = {
to = 'Your Target <target email>',
subject = subject
},
body = body
}
local ok, err = smtp.send {
from = '<your email>',
rcpt = '<target email>',
source = smtp.message(msg),
user = 'username',
password = 'password',
server = 'smtp.gmail.com',
port = 465,
create = sslCreate
}
if not ok then
print("Mail send failed", err) -- better error handling required
end
end
The code works good if I send something from gmail. But when I use godaddy smtp server which is smtpout.secureserver.net (same port) it fails to send the message. I just get error code 550.
Please can anyone help me figure out how to make this work.
Thanks.
It worked thanks to this post:
Trying to send email to Google through in Python, email being denied
I just changed the code to add the from field in the headers table like this:
-- Michal Kottman, 2011, public domain
local socket = require 'socket'
local smtp = require 'socket.smtp'
local ssl = require 'ssl'
local https = require 'ssl.https'
local ltn12 = require 'ltn12'
function sslCreate()
local sock = socket.tcp()
return setmetatable({
connect = function(_, host, port)
local r, e = sock:connect(host, port)
if not r then return r, e end
sock = ssl.wrap(sock, {mode='client', protocol='tlsv1'})
return sock:dohandshake()
end
}, {
__index = function(t,n)
return function(_, ...)
return sock[n](sock, ...)
end
end
})
end
function sendMessage(subject, body)
local msg = {
headers = {
from = "<your email>",
to = 'Your Target <target email>',
subject = subject
},
body = body
}
local ok, err = smtp.send {
from = '<your email>',
rcpt = '<target email>',
source = smtp.message(msg),
user = 'username',
password = 'password',
server = 'smtp.gmail.com',
port = 465,
create = sslCreate
}
if not ok then
print("Mail send failed", err) -- better error handling required
end
end

lua send mail with gmail account

I want to send email with my gmail account, I gave it a try, but no luck, so is anyone can give me a sample? Any suggestions would be appreciated. Thank you
I used lualogging api, the code is
require"logging.email"
logger = logging.email {
rcpt = "aaa#sina.com",
from = "bbb#gmail.com",
user = "bbb#gmail.com",
password = *****,
server = "smtp.gmail.com",
port = 587,
headers = {
rcpt = "aaa#sina.com",
from = "bbb#gmail.com",
subject = "[%level] logging.email test",
},
}
logger:error("error!")
You should look at LuaSocket, especially its SMTP module which can be used to send mail using your GMail account. You also need a SSL library, I use LuaSec which was designed to be used together with LuaSocket. This is the code I successfully used to send emails using my GMail account:
-- Michal Kottman, 2011, public domain
local socket = require 'socket'
local smtp = require 'socket.smtp'
local ssl = require 'ssl'
local https = require 'ssl.https'
local ltn12 = require 'ltn12'
function sslCreate()
local sock = socket.tcp()
return setmetatable({
connect = function(_, host, port)
local r, e = sock:connect(host, port)
if not r then return r, e end
sock = ssl.wrap(sock, {mode='client', protocol='tlsv1'})
return sock:dohandshake()
end
}, {
__index = function(t,n)
return function(_, ...)
return sock[n](sock, ...)
end
end
})
end
function sendMessage(subject, body)
local msg = {
headers = {
to = 'Your Target <target email>',
subject = subject
},
body = body
}
local ok, err = smtp.send {
from = '<your email>',
rcpt = '<target email>',
source = smtp.message(msg),
user = 'username',
password = 'password',
server = 'smtp.gmail.com',
port = 465,
create = sslCreate
}
if not ok then
print("Mail send failed", err) -- better error handling required
end
end
The code from Michal Kottman works properly but it fails (for me) when smpt server works on 587 port, using a pretty different way to accept mail to send (according wo what I read). Does anybody faced anything similar? I always obtain "wrong version number" on server working on port 587.

stream_socket_server: Client browser randomly aborting?

Below is partial code to an experimental http server app I'm building from scratch from a PHP CLI script (Why? Because I have too much time on my hands). The example below more closely matches PHP's manual page on this function. The problem I'm getting is when connecting to this server app via a browser (Firefox or IE8 from two separate systems tested so far), the browser sends an empty request payload to the server and aborts roughly every 1 in 6 page loads.
The server console displays the "Connected with [client info]" each time. However, about 1 in 6 connections will result in a "Client request is empty" error. No error is given telling the header/body response write to the socket failed. The browser will generally continue to read what I give it, but this isn't usable as I can't fulfill the client's intended request without knowing what it is.
<?php
$s_socket_uri = 'tcp://localhost:80';
// establish the server on the above socket
$s_socket = stream_socket_server($s_socket_uri, $errno, $errstr, 30) OR
trigger_error("Failed to create socket: $s_socket_uri, Err($errno) $errstr", E_USER_ERROR);
$s_name = stream_socket_get_name($s_socket, false) OR
trigger_error("Server established, yet has no name. Fail!", E_USER_ERROR);
if (!$s_socket || !$s_name) {return false;}
/*
Wait for connections, handle one client request at a time
Though to not clog up the tubes, maybe a process fork is
needed to handle each connection?
*/
while($conn = stream_socket_accept($s_socket, 60, $peer)) {
stream_set_blocking($conn, 0);
// Get the client's request headers, and all POSTed values if any
echo "Connected with $peer. Request info...\n";
$client_request = stream_get_contents($conn);
if (!$client_request) {
trigger_error("Client request is empty!");
}
echo $client_request."\n\n"; // just for debugging
/*
<Insert request handling and logging code here>
*/
// Build headers to send to client
$send_headers = "HTTP/1.0 200 OK\n"
."Server: mine\n"
."Content-Type: text/html\n"
."\n";
// Build the page for client view
$send_body = "<h1>hello world</h1>";
// Make sure the communication is still active
if ((int) fwrite($conn, $send_headers . $send_body) < 1) {
trigger_error("Write to socket failed!");
}
// Response headers and body sent, time to end this connection
stream_socket_shutdown($conn, STREAM_SHUT_WR);
}
?>
Any solution to bring down the number of unintended aborts down to 0, or any method to get more stable communication going? Is this solvable on my server's end, or just typical browser behavior?
I tested your code and it seems I got better results reading the socket with fread(). You also forgot the main loop(while(1), while(true) or for(;;).
Modifications to your code:
stream_socket_accept with #stream_socket_accept [sometimes you get warnings because "the connected party did not properly respond", which is, of course, the timeout of stream_socket_accept()]
Added the big while(1) { } loop
Changed the reading from the socket from $client_request = stream_get_contents($conn);
to while( !preg_match('/\r?\n\r?\n/', $client_request) ) { $client_request .= fread($conn, 1024); }
Check the source code below (I used 8080 port because I already had an Apache listening on 80):
<?php
$s_socket_uri = 'tcp://localhost:8080';
$s_socket = stream_socket_server($s_socket_uri, $errno, $errstr, 30) OR
trigger_error("Failed to create socket: $s_socket_uri, Err($errno) $errstr", E_USER_ERROR);
$s_name = stream_socket_get_name($s_socket, false) OR
trigger_error("Server established, yet has no name. Fail!", E_USER_ERROR);
if (!$s_socket || !$s_name) {return false;}
while(1)
{
while($conn = #stream_socket_accept($s_socket, 60, $peer))
{
stream_set_blocking($conn, 0);
echo "Connected with $peer. Request info...\n";
// $client_request = stream_get_contents($conn);
$client_request = "";
// Read until double \r
while( !preg_match('/\r?\n\r?\n/', $client_request) )
{
$client_request .= fread($conn, 1024);
}
if (!$client_request)
{
trigger_error("Client request is empty!");
}
echo $client_request."\n\n";
$headers = "HTTP/1.0 200 OK\n"
."Server: mine\n"
."Content-Type: text/html\n"
."\n";
$body = "<h1>hello world</h1><br><br>".$client_request;
if ((int) fwrite($conn, $headers . $body) < 1) {
trigger_error("Write to socket failed!");
}
stream_socket_shutdown($conn, STREAM_SHUT_WR);
}
}
Add sleep(1) after stream_set_blocking